MongoDB2.6, java Usage Details

Source: Internet
Author: User
Tags mongodb download
The environment used in this article is: win7_64 + Eclipse + maven I. Preparations for downloading the java driver package: mvnrepository. comartifactorg. mongodbmongo-java-drivermongoDB download: www.mongodb.org online api: docs. mongodb. orgmanualapplicationsdr

The environment used in this article is: win7_64 + Eclipse + maven, preparation to download java driver package: http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver mongoDB download: http://www.mongodb.org/online api: http://docs.mongodb.org/manual/applications/dr

The environment used in this article is: win7_64 + Eclipse + maven I. PreparationsDownload the java driver package
Driver Pack: http://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
MongoDB http://www.mongodb.org/
Api: http://docs.mongodb.org/manual/applications/drivers/ Ii. Install Mongo1. Installation Method in windows:
   Install the Mongo database:
Step 1: Download the installation package: if it is a Windows system, check whether it is a 64-bit or 32-bit version. Select the correct version.
Step 2: Create the directory "D: \ mongodb.pdf", decompress the downloaded installation package, find the directory "all-part. EXE", and copy it to the directory you just created.
Step 3: create a "data" folder under the "D: \ MongoDB" Directory, which will be used as the root folder for data storage.
   Configure the Mongo Server:
Open the CMD window and enter the command as follows:
> D:
> Cd D: \ MongoDB
> Mongod -- dbpath D: \ MongoDB \ data
After successful startup, access: http: // localhost: 27017/from the browser/

Indicates that mongodb in windows has been started successfully;
2. linux installation method:
After downloading and decompressing the package, make sure that the remaining space in the database directory is 3 GB or above;
Start with the configuration file: create a file named mongodb. conf in the root directory of mongodb. The content is as follows:
# Fork = true # Run as a daemon, create a server process # master = true # set as the master server for a single master-slave configuration # salve = true # set as the slave server for a single master-slave configuration # replSet = blort # Set the full set name # shardsvr = true # Set whether to slice # 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 =/ mongodb2.6.3/data # Database path logpath =/mongodb2.6.3/logs/mongodb. log # log output file path logappend = true # log output mode directoryperdb = true noauth = true port = 8888 # port number maxConns = 1024 fork = true quota = true quotaFiles = 1024 nssize = 16

The startup method is as follows:/mongodb2.6.3/bin/mongod-f/mongodb2.6.3/mongodb. conf
Remember to enable the linux Access Port:
# Vi/etc/sysconfig/iptables
Yy copy a row
P Paste
Modify Port
# Service iptables restart
Set auto-start
# Echo/mongodb2.6.3/bin/mongod-f/mongodb2.6.3/mongodb. config>/etc/rc. local

After the database is started, create the database and set:
Mongo -- port 8888

> Show dbs
Admin (empty)
Local 0.078 GB
> Use admin (switch Management User)
Switched to db admin
> Db. mymongo (create database)
Admin. mymongo
> Db. addUser ("root", "root") (Add User)
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 (display 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 deletes a database
Use mymongo;
Db. dropDatabase ();
Mongodb table Deletion
Db. t_users.drop ();
MongoDB Service stopped:
In linux, if you stop many services and like to directly kill-9 PID, But if you execute kill-9 PID for MongoDB, an error may be prompted at the next startup, resulting in service failure, in this case, run the following command:
Java code
Rm-f/app/hadoop/db/mongod. lock: Delete the mongod. lock file in the specified data directory.

Normal stop method:
Kill-2 PID
Or
Java code
./Mongo-host ip: port first connects to the service to be stopped, and then:
Java code
> Use admin> db. shutdownServer ();
In this way, the service can be stopped normally. Iii. Java MongoDB operation example

1. Create Test. java to complete simple mongoDB database operations

Try {Mongo mg = new Login client ("192.168.186.129", 8888); DB db DB = mg. getDB ("mymongo"); // used to determine user logon // if (! Db. authenticate ("sdap", "sdap123". toCharArray () {// The method is not recommended. //} Set
 
  
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 (" 1aaa"); u. setTp (12); String obj2Json = JsonUtils. getSingletonInstance (). obj2Json (u); BasicDBObject dbObject1 = new BasicDBObject (); dbObject1.put ("key", "123131"); Aggregate ("value", obj2Json); collection2.save (dbObject1 );
  
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());}} catch (UnknownHostException e) {            e.printStackTrace();                    }

The following is my mongodb tool class:

/*** Project Name: main * File Name: MongodbCacheManagerUtil. java * Package Name: com. hdsx. taxi. driver. cq. cache * Date: April 9, 2014 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. using client;/*** ClassName: MongodbCacheManagerUtil * Function: todo add function. * Reason: todo add reason. * Date: April 9, 2014 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. 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); db = 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 to be cached to 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 :( get the object from the specified cache object based on the key ). ** @ author sid * @ param cacheName * @ param key * @ return */public
   
    
T get (String cacheName, String key, Class
    
     
ClassOfT) {DBCollection cache = this. db. getCollection (cacheName); List
     
      
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 :( clear 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 keys list ). ** @ author sid * @ param cacheName * @ return */public List
      
       
GetKeys (String cacheName) {List
       
        
List = new ArrayList
        
          (); 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 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 ;}} besides save, insert, update, mongodb, and remove
        
       
      
     
    
   

The find method can specify the query conditions:

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.