Java operations on MongoDB

Source: Internet
Author: User
Tags findone mongodb example

Development Environment:

System: Windows

IDE: Eclipse and myeclipse 8

Database: MongoDB

Development dependency Library:

Javaee5, mongo-2.5.3.jar, junit-4.8.2.jar

I. Preparations

1. First, download the driver packages supported by MongoDB for Java.

Driver Pack: https://github.com/mongodb/mongo-java-driver/downloads

MongoDB Java-related support, technology: http://www.mongodb.org/display/DOCS/Java+Language+Center

Driver source code download: https://download.github.com/mongodb-mongo-java-driver-r2.6.1-7-g6037357.zip

Source code: https://github.com/mongodb/mongo-java-driver

2. Create a javaproject project to import the downloaded driver package. You can use MongoDB in Java. The directory is as follows:

Ii. Java MongoDB operation example

Before this example, you can start the mongod.exe service. After the service is started, the following program can be successfully executed;

1. Create simpletest. Java to complete simple MongoDB database operations

Mongo mongo = new Mongo();

In this way, a MongoDB database connection object is created, which is connected to the localhost address of the current machine by default, and the port is 27017.

DB db = mongo.getDB(“test”);

In this way, a database named test is obtained. If this database is not created in MongoDB, it can run normally. If you have read the previous article, you will know that MongoDB can add data without creating this database. When this database is not added, MongoDB automatically creates the current database.

After obtaining the DB, we will get a "clustered collection dbcollection" and use the getcollection method of the DB object.

DBCollection users = db.getCollection("users");

In this way, a dbcollection is obtained, which is equivalent to the "table" of our database ".

Query all data

DBCursor cur = users.find();while (cur.hasNext()) {System.out.println(cur.next());}

1. Testing

Package COM. hoo. test; import java.net. unknownhostexception; import COM. mongoDB. DB; import COM. mongoDB. dbcollection; import COM. mongoDB. dbcursor; import COM. mongoDB. mongo; import COM. mongoDB. except exception; import COM. mongoDB. util. JSON;/*** <B> function: </B> simple MongoDB example * @ author hoojo * @ createdate 02:42:29 * @ file simpletest. java * @ package COM. hoo. test * @ project MongoDB * @ blog http://blog.csdn.net/IBM_hoojo * @ email hoojo_@126.com * @ version 1.0 */public class simpletest {public static void main (string [] ARGs) throws unknownhostexception, except exception {Mongo Mg = new Mongo (); // query all databases for (string name: Mg. getdatabasenames () {system. out. println ("dbname:" + name);} dB DB = Mg. getdb ("test"); // query all aggregation sets for (string name: DB. getcollectionnames () {system. out. println ("collectionname:" + name);} dbcollection users = dB. getcollection ("users"); // query all data dbcursor cur = users. find (); While (cur. hasnext () {system. out. println (cur. next ();} system. out. println (cur. count (); system. out. println (cur. getcursorid (); system. out. println (JSON. serialize (cur ));}}

2. To complete the CRUD operation, first create mongodb4crudtest. java. The basic test code is as follows:

Package COM. hoo. test; import java.net. unknownhostexception; import Java. util. arraylist; import Java. util. list; import Org. bson. types. objectid; import Org. JUnit. after; import Org. JUnit. before; import Org. JUnit. test; import COM. mongoDB. basicdbobject; import COM. mongoDB. bytes; import COM. mongoDB. DB; import COM. mongoDB. dbcollection; import COM. mongoDB. dbcursor; import COM. mongoDB. dbobject; import COM. mongoDB. mongo; Import COM. mongoDB. except exception; import COM. mongoDB. queryoperators; import COM. mongoDB. util. JSON;/*** <B> function: </B> implement the CRUD operation for MongoDB * @ author hoojo * @ createdate 2011-6-2 03:21:23 * @ file mongodb4crudtest. java * @ package COM. hoo. test * @ project MongoDB * @ blog http://blog.csdn.net/IBM_hoojo * @ email hoojo_@126.com * @ version 1.0 */public class mongodb4crudtest {private Mongo Mg = NULL; PRI Vate dB; private dbcollection users; @ before public void Init () {try {Mg = new Mongo (); // Mg = new Mongo ("localhost", 27017 );} catch (unknownhostexception e) {e. printstacktrace ();} catch (except exception e) {e. printstacktrace ();} // get temp dB. If no temp dB is created by default, MongoDB automatically creates DB = Mg. getdb ("Temp"); // get users dbcollection; if it is not created by default, MongoDB will automatically create users = dB. getcollection ("users") ;}@ after public void des Else () {If (Mg! = NULL) mg. close (); Mg = NULL; DB = NULL; users = NULL; system. GC ();} public void print (Object O) {system. out. println (o );}}

3. Add operation. Before adding an operation, we need to write a query method to query all the data. The Code is as follows:

/*** <B> function: </B> query all data * @ author hoojo * @ createdate 2011-6-2 03:22:40 */private void queryall () {print ("query all users data:"); // dB cursor dbcursor cur = users. find (); While (cur. hasnext () {print (cur. next () ;}@ testpublic void add () {// first query all data queryall (); print ("count:" + users. count (); dbobject user = new basicdbobject (); User. put ("name", "hoojo"); User. put ("Age", 24); // users. save (User) Save, getn () get affected rows // print (users. save (user ). getn (); // extended field. Add the field at will without affecting the user of the existing data. put ("sex", "male"); print (users. save (user ). getn (); // Add multiple data records and pass the print (users. insert (user, new basicdbobject ("name", "Tom ")). getn (); // Add list set list <dbobject> List = new arraylist <dbobject> (); list. add (User); dbobject user2 = new basicdbobject ("name", "Lucy"); User. put ("Age", 22); list. add (user2); // Add the print (users. insert (list ). getn (); // query the data to see if print ("count:" + users. count (); queryall ();}

4. delete data

@ Testpublic void remove () {queryall (); print ("delete id = 4de73f7acd812d61b4626a77:" + users. remove (New basicdbobject ("_ id", new objectid ("4de73f7acd812d61b4626a77 "))). getn (); print ("remove age> = 24:" + users. remove (New basicdbobject ("Age", new basicdbobject ("$ GTE", 24 ))). getn ());}

5. modify data

@ Testpublic void modify () {print ("Modify:" + users. update (New basicdbobject ("_ id", new objectid ("4dde25d06be7c53ffbd70906"), new basicdbobject ("Age", 99 )). getn (); print ("Modify:" + users. update (New basicdbobject ("_ id", new objectid ("4dde2b06feb038463ff09042"), new basicdbobject ("Age", 121), true, // if the database does not exist, whether to add false // multiple modifications ). getn (); print ("Modify:" + users. update (New basicdbobject ("name", "Haha"), new basicdbobject ("name", "Dingding"), true, // if the database does not exist, whether to add true // false. Only the first day is modified. True is not modified if there are multiple values ). getn (); // if the database does not exist, it is not modified or added. If multiple data entries exist, it is not modified. // print ("Modify multiple entries:" + Coll. updatemulti (New basicdbobject ("_ id", new objectid ("4dde23616be7c19df07db42c"), new basicdbobject ("name", "199 ")));}

6. query data

@ Testpublic void query () {// query all // queryall (); // query ID = 4de73f7acd812d61b4626a77 print ("find id = 4de73f7acd812d61b4626a77:" + users. find (New basicdbobject ("_ id", new objectid ("4de73f7acd812d61b4626a77 "))). toarray (); // query age = 24 print ("find age = 24:" + users. find (New basicdbobject ("Age", 24 )). toarray (); // query age> = 24 print ("find age> = 24:" + users. find (New basicdbobject ("Age", new basicdbo Bject ("$ GTE", 24 ))). toarray (); print ("find age <= 24:" + users. find (New basicdbobject ("Age", new basicdbobject ("$ LTE", 24 ))). toarray (); print ("query age! = 25: "+ users. find (New basicdbobject ("Age", new basicdbobject ("$ ne", 25 ))). toarray (); print ("query age in 25/26/27:" + users. find (New basicdbobject ("Age", new basicdbobject (queryoperators. in, new int [] {25, 26, 27 }))). toarray (); print ("query age not in 25/26/27:" + users. find (New basicdbobject ("Age", new basicdbobject (queryoperators. nin, new int [] {25, 26, 27 }))). toarray (); print ("query age exists sorting:" + users. find (New basicdbobject ("Age", new basicdbobject (queryoperators. exists, true ))). toarray (); print ("only query age attributes:" + users. find (null, new basicdbobject ("Age", true )). toarray (); print ("only query attributes:" + users. find (null, new basicdbobject ("Age", true), 0, 2 ). toarray (); print ("only query attributes:" + users. find (null, new basicdbobject ("Age", true), 0, 2, bytes. queryoption_notimeout ). toarray (); // query only one piece of data, multiple entries go to the first print ("findone:" + users. findone (); print ("findone:" + users. findone (New basicdbobject ("Age", 26); print ("findone:" + users. findone (New basicdbobject ("Age", 26), new basicdbobject ("name", true ))); // query, modify, and delete print ("findandremove, query data of age = 25, and delete:" + users. findandremove (New basicdbobject ("Age", 25); // query data with age = 26 and change the value of name to ABC print ("findandmodify:" + users. findandmodify (New basicdbobject ("Age", 26), new basicdbobject ("name", "ABC"); print ("findandmodify:" + users. findandmodify (New basicdbobject ("Age", 28), // query data of age = 28 new basicdbobject ("name", true ), // query the name attribute new basicdbobject ("Age", true), // sort by age to false, // whether to delete, true means to delete new basicdbobject ("name ", "ABC"), // modify the value, and change the name to ABC true, true); queryall ();}

MongoDB does not support joint queries and subqueries, which must be completed in the program. Filter the query result set in the Java query.

7. Other operations

Public void testothers () {dbobject user = new basicdbobject (); User. put ("name", "hoojo"); User. put ("Age", 24); // converts a JSON object to print ("serialize:" + JSON. serialize (User); // deserialize print ("parse:" + JSON. parse ("{\" Name \ ": \" hoojo \ ", \" Age \ ": 24}"); print ("determine whether the temp collection exists: "+ dB. collectionexists ("Temp"); // create if (! DB. collectionexists ("Temp") {dbobject Options = new basicdbobject (); options. put ("size", 20); options. put ("Capped", 20); options. put ("Max", 20); print (dB. createcollection ("Account", options);} // set the database to read-only DB. setreadonly (true); // read-only data cannot be written to the database. getcollection ("test "). save (User );}

From: http://www.cnblogs.com/hoojo/archive/2011/06/02/2068665.html

Related Article

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.