Mongodb2.6,java use of the detailed

Source: Internet
Author: User

The environment used in this article is: Win7_64+eclipse+maven
First, the preparatory work

Download Java driver package

Drive Pack: 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, installation MONGO

1.windows Installation Method:

  To install the MONGO database:

First step: Download the installation package: If it is a win system, note whether it is a 64-bit or 32-bit version, please select the correct version.

Second step: Create a new directory "D:\MongoDB", unzip the downloaded installation package, locate all the. exe files under the bin directory, and copy to the directory you just created.

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

  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 MongoDB under Windows has started successfully;

2.linux Installation Method:

After download to ensure that the database directory size remaining space above 3G;

This is started with the configuration file: Create a file named: Mongodb.conf at the root of MongoDB, with the following content:

The starting mode is as follows:/mongodb2.6.3/bin/mongod-f/mongodb2.6.3/mongodb.conf
Remember to open the access port for Linux:

#vi/etc/sysconfig/iptables

YY Copy a row

P Paste

Modify Port

#service iptables Restart

Set up boot from

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


The database starts, and then the database and the collection are created:

MONGO--port 8888


> Show DBS
Admin (empty)
Local 0.078GB
> Use admin(switch administrative users)
Switched to DB admin
> Db.mymongo(CREATE DATABASE)
Admin.mymongo
> Db.adduser ("Root", "root")(add users)
Warning:the ' AddUser ' shell Helper is DEPRECATED. Please 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(show table)
System.indexes
System.users
System.version
T_users
> Db.t_users.save ({age:21})(store 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 everyone stop a lot of services like Direct kill-9 PID, but for MongoDB if the kill-9 PID, the next boot may prompt error, cause the service cannot start, this time can be executed by:

Java code
    1. Rm-f/app/hadoop/db/mongod.lock
You can also delete the Mongod.lock file under the specified data directory.

Normal Stop method:
Kill-2 PID
Or
Java code
    1. ./mongo-host Ip:port
First connect the services that need to be stopped, and then:
Java code
    1. >use Admin
    2. >db.shutdownserver ();

This can also stop the service as normal.

Iii. Java Operation MongoDB Example

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

try {Mongo mg = new Mongoclient ("192.168.186.129", 8888);D b DB = Mg.getdb ("Mymongo");//used to determine user login//if ( !db.authenticate ("Sdap", "sdap123". ToCharArray ())) {//method has not been recommended for use with//}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 ("Beijing 1aaa"); U.settp (12); String Obj2json = Jsonutils.getsingletoninstance (). Obj2json (U); Basicdbobject dbobject1=new basicdbobject ();d bobject1.put ("Key", "123131");d bobject1.put ("value", Obj2json); Collection2.save (DbObject1); <pre name= "code" class= "java" >basicdbobject dbobject=new Basicdbobject (); Dbobject.put ("Key", "123131");D bcursor 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 ());}} catch (unknownhostexception e) {            e.printstacktrace ();                     }

The following is a tool class that stickers my own MongoDB:

/** * Project Name:main * File Name:MongodbCacheManagerUtil.java * Package Name:com.hdsx.taxi.driver.cq.cache * date:2014 April 9 pm 12:49:55 * Copyright (c), 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 pm 12:49:55 * @author SID * @see */public class Mongodbmanagerutil {private static final Logger Logger = Logger.getlogger (mongodbmanagerutil.class);p rivate Mongo mg = null;private db db = null;private volatile statIC Mongodbmanagerutil singleton = null;public static final string key = "KEY";p ublic static final String value = "VALUE";p Ublic static Mongodbmanagerutil getsingletoninstance () {if (singleton = = null) {synchronized (Mongodbmanagerutil.class) {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);d B = Mg.getdb ("Mymongo");} catch (Unknownhostexception e) {e.printstacktrace ();} if (logger.isdebugenabled ()) {Logger.debug ("mongodbcachemanagerutil ()-end");//$NON-nls-1$}}/** * * GetCache: (Get Cache object  ). * * @author SID * @param name * @return */public dbcollection getcache (String name) {return this.db.getCollection (name);}  /** * Put: (add the object that needs to be cached in the specified cache object). * * @author SID * @param cachename * @param key * @param value */public void put (String cachename,String key, 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 based on key). * * @author SID * @param cachename * @param key * @return */public <T> T get (String Cachenam         E, 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 objects 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&lt ;        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: (determines whether the message exists). * * @Author SID * @param cachename * @param key * @return */public Boolean containskey (String cachename,string key) {DBC        Ollection 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 to: $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.