Mongodb2.6,java Use detailed

Source: Internet
Author: User
The environment used in this article is: Win7_64+eclipse+maven
First, preparatory work

Download Java driver package

Driver package Download Address: Http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver

MongoDB Download: http://www.mongodb.org/

Online api:http://docs.mongodb.org/manual/applications/drivers/

Second, install MONGO

1.windows installation mode:

  To install the MONGO database:

The first step: Download the installation package: If the win system, note that 64-bit or 32-bit version, please select the correct version.

Step Two: Create a new directory "D:\MongoDB", unzip the download to the installation package, find the bin directory with all the. exe files, copy to the directory just created.

Step three: Create a new "data" folder under the "D:\MongoDB" directory, which will be the root folder for the data.

  Configure the MONGO service side:

Open the cmd window and enter the command as follows:
> D:
> CD D:\MongoDB
> Mongod--dbpath D:\MongoDB\data

Access from browser after successful startup: http://localhost:27017/

Indicates that the MongoDB under Windows have been started successfully;

2.linux installation mode:

After the download decompression to ensure that the database directory size of the remaining space in more than 3G;

This is started using a configuration file: Create a file named: mongodb.conf in the root directory of MongoDB, which reads:

#fork =true #以守护进程的方式运行, create server process

# #master =true #单主从配置时设为主服务器

# #salve =true # #单主从配置时设为从服务器 #replSet

=blort #设置富本集的名字

#shardsvr =true #设置是否分片

#repairpath =/mongodb2.6.3/repair 
#pidfilepath =/mongodb2.6.3/ Mongodb.pid 
#sysinfo = True 
#verbose = True 
#cpu = True 
#Network and security set 
#Management 
#nohttpinterface = True 
#rest = True 
#syncdelay = 5

#Directory and relavent set 
DBPath =/mongo Db2.6.3/data #数据库路径
logpath =/mongodb2.6.3/logs/mongodb.log #日志输出文件路径
logappend = True #日志输出方式
Directoryperdb = True 
Noauth = true 
port = 8888 #端口号
Maxconns = 1024 Fork 
= true 
quota = True
  quotafiles = 1024 
nssize = 16 

The starting mode is as follows:/mongodb2.6.3/bin/mongod-f/mongodb2.6.3/mongodb.conf
Remember to turn on Linux access ports:

#vi/etc/sysconfig/iptables

YY Copy Row

P Paste

Modify Port

#service iptables Restart

Set up startup

#echo/mongodb2.6.3/bin/mongod-f/mongodb2.6.3/mongodb.config >>/etc/rc.local


The database is started and then the database and collection are created:

MONGO--port 8888
> Show DBS
Admin (empty)
Local 0.078GB
> Use admin (switch Admin user)
Switched to DB admin
> Db.mymongo (CREATE DATABASE)
Admin.mymongo
> Db.adduser ("Root", "root") (add user)
Warning:the ' AddUser ' shell helper is deprecated. Use ' CreateUser ' instead
Successfully added User: {"user": "Root", "roles": ["Root"]}
> Db.auth ("Root", "root") (add login user)
1
> db.createcollection ("T_users") (Add table)
{"OK": 1}
> Show collections (Display table)
System.indexes
System.users
System.version
T_users
> Db.t_users.save ({age:21}) (storing data)
Writeresult ({"ninserted": 1})
> Db.t_users.find () (Query all data)
{"_id": ObjectId ("53a2e45e4a674863b4ac5398"), "Age": 21}

MongoDB Delete Database

Use Mymongo;

Db.dropdatabase ();

MongoDB Delete Table

Db.t_users.drop ();


MongoDB Service stopped:
In Linux, we stop a lot of services like the direct kill-9 PID, but for MongoDB if the kill-9 PID, the next boot may be prompted to error, causing the service can not start, this time by executing:
Java code rm-f/app/hadoop/db/mongod.lock also deletes the Mongod.lock file in the specified data directory.

Normal Stop method:
Kill-2 PID
Or
Java code./mongo-host Ip:port First connect the service that needs to be stopped, and then:
Java Code >use Admin >db.shutdownserver ();
This can also stop the service normally.

Java Operation MongoDB Example

1, establish Test.java, complete the simple MongoDB database operation

try {Mongo mg = new Mongoclient ("192.168.186.129", 8888);
DB db = Mg.getdb ("Mymongo"); Used to determine user login//if (!db.authenticate ("Sdap", "sdap123". ToCharArray ())) {//method has not recommended//} Set
			<String> collectionnames = Db.getcollectionnames ();
			for (string string:collectionnames) {System.out.println (string);
			} dbcollection Collection2 = Db.getcollection ("T_users2");
			Collection2 = Db.getcollection ("T_users2");
			Carpasitionobj u = new Carpasitionobj ();
			U.setla (1231D);
			U.setlo (42342d);
			U.SETPN ("Jing 1aaa");
			U.settp (12);
			String Obj2json = Jsonutils.getsingletoninstance (). Obj2json (U);
			Basicdbobject dbobject1=new basicdbobject ();
			Dbobject1.put ("Key", "123131");
			Dbobject1.put ("value", Obj2json);
			Collection2.save (DBOBJECT1);
			<pre name= "code" class= "java" > Basicdbobject dbobject=new basicdbobject ();
			Dbobject.put ("Key", "123131");
			Dbcursor find = Collection2.find (dbobject);
			while (Find.hasnext ()) {	DBObject next = Find.next ();
				String key = (string) next.get ("key");
				String json = (string) next.get ("value");
				SYSTEM.OUT.PRINTLN (key);
				Carpasitionobj Formjson = Jsonutils.getsingletoninstance (). Formjson (JSON, carpasitionobj.class);
			System.out.println (FORMJSON.GETPN ());
The catch (Unknownhostexception e) {            e.printstacktrace ();
                      

Here's my own MongoDB tool class:

/** * Project Name:main * File Name:MongodbCacheManagerUtil.java * Package Name:com.hdsx.taxi.driver.cq.cache * date:2
 014 April 9 Afternoon 12:49:55 * Copyright (c) 2014, Sid Jenkins all Rights Reserved.

* * * * * * * Package com.hdsx.taxi.driver.cq.mongodb;
Import java.net.UnknownHostException;
Import java.util.ArrayList;

Import java.util.List;

Import Org.apache.log4j.Logger;
Import Com.hdsx.taxi.driver.cq.module.InitServletModule;
Import Com.hdsx.taxi.driver.cq.tcp.util.JsonUtils;
Import Com.mongodb.BasicDBObject;
Import Com.mongodb.DB;
Import com.mongodb.DBCollection;
Import Com.mongodb.DBCursor;
Import Com.mongodb.DBObject;
Import Com.mongodb.Mongo;


Import com.mongodb.MongoClient; 
 /** * Classname:mongodbcachemanagerutil * Function:todo ADD Function. 
 * Reason:todo ADD Reason. * date:2014 April 9 Afternoon 12:49:55 * @author SID * @see/public class Mongodbmanagerutil {private static final

	Logger Logger = Logger.getlogger (Mongodbmanagerutil.class); Private Mongo mg = nulL
	
	Private db db = null;
	
	Private volatile static mongodbmanagerutil singleton = null;
	
	public static final String key = "key";
	
	public static final String value = "value"; public static Mongodbmanagerutil Getsingletoninstance () {if (singleton = null) {synchronized (mongodbmanagerutil.c
				Lass) {if (singleton = = null) {singleton = new mongodbmanagerutil ();
		} singleton = new Mongodbmanagerutil ();
	return singleton;  Private Mongodbmanagerutil () {if (logger.isdebugenabled ()) {Logger.debug ("Mongodbcachemanagerutil ()-start");
				$NON-nls-1$} try {mg = new Mongoclient ("192.168.186.129", 8888);
			db = Mg.getdb ("Mymongo");
				
			catch (Unknownhostexception e) {e.printstacktrace (); 
	 } if (logger.isdebugenabled ()) {Logger.debug ("mongodbcachemanagerutil ()-end");//$NON-nls-1$}}/** * 
	 * GetCache: (Gets the cached object). * @author SID * @param name * @return/Public dbcollection getcache (String naMe) {return this.db.getCollection (name); 
	 /** * Put: (add objects that need to be cached in the specified cache object). * @author SID * @param cachename * @param key * @param value/public void put (string cachename, String k
		EY, Object value) {dbcollection cache = this.db.getCollection (cachename);
		String Obj2json = Jsonutils.getsingletoninstance (). Obj2json (value);
		Basicdbobject obj = new Basicdbobject ();
		Obj.put (Mongodbmanagerutil.key, KEY);
        Obj.put (Mongodbmanagerutil.value, Obj2json);
        Basicdbobject basicdbobject = new Basicdbobject (Mongodbmanagerutil.key, KEY);
        int size = Cache.find (basicdbobject). Count ();
		if (size==0) {cache.save (obj);
		}else{cache.update (basicdbobject, obj); 
     }/** * * Get: (Gets the object from the specified cache object according to key). * @author SID * @param cachename * @param key * @return/public <T> T get (String CA Chename, String key, class<t> classoft) {dbcollection cache = thIs.db.getCollection (CacheName);
        list<dbobject> array = cache.find (new Basicdbobject (Mongodbmanagerutil.key, KEY)). ToArray (); if (array = = null| |
		Array.size () ==0) {return null;
        } dbobject dbobject = array.get (0);
        
        String json = (string) dbobject.get (Mongodbmanagerutil.value); 
    Return Jsonutils.getsingletoninstance (). Formjson (JSON, classoft); 
     /** * Remove: (clears the object from the specified cache object). * @author SID * @param cachename * @param key/public void Remove (string cachename, String key
        ) {Dbcollection cache = this.db.getCollection (cachename);
    Cache.remove (New Basicdbobject (Mongodbmanagerutil.key,key)); 
     }/** * * Getkeys: (Get the Keys list).
		* * @author SID * @param cachename * @return/Public list<string> Getkeys (String cachename) {
        list<string> list = new arraylist<string> (); Dbcollection cache = ThiS.db.getcollection (CacheName);
        Dbcursor find = Cache.find ();
        	while (Find.hasnext ()) {DBObject next = Find.next ();
        	String key = (string) next.get (Mongodbmanagerutil.key);
		List.add (key);
    } return list; 
	 }/** * * ContainsKey: (To determine if a message exists).  * @author SID * @param cachename * @param key * @return/Public Boolean containskey (String cachename,string
        Key) {Dbcollection cache = this.db.getCollection (cachename);
        Basicdbobject basicdbobject = new Basicdbobject (Mongodbmanagerutil.key, KEY);
        int size = Cache.find (basicdbobject). Count ();
		if (size==0) {return false;
		}else{return true;

 }
	}
}
In addition to save, insert, Update;mongodb and remove operations

Where the Find method can specify the query criteria:

Greater than or equal to: $gte

Less than or equal: $lte

Not equal to: $ne

Demo:users.find (New Basicdbobject ("Age", New Basicdbobject ("$gte", 24))


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.