"MongoDB for Java" Java Operation MongoDB

Source: Internet
Author: User
Tags findone mongodb example mongodb support






Previous article: Http://www.cnblogs.com/hoojo/archive/2011/06/01/2066426.html introduced to the MONGODB console to complete the data manipulation of MongoDB, We have a comprehensive understanding and understanding of MongoDB through the previous article. Now we're going to use Java to manipulate MongoDB data.












Development environment:






System:windows






Ide:eclipse, MyEclipse 8






Database:mongodb






Developing dependent libraries:






JavaEE5, Mongo-2.5.3.jar, Junit-4.8.2.jar






Email:[email protected]






Blog:http://blog.csdn.net/ibm_hoojo






http://hoojo.cnblogs.com/










First, the preparatory work



1. First, download MongoDB support for Java driver package






Drive Pack: Https://github.com/mongodb/mongo-java-driver/downloads






MongoDB support for Java, technology: Http://www.mongodb.org/display/DOCS/Java+Language+Center






Drive Source Download: Https://download.github.com/mongodb-mongo-java-driver-r2.6.1-7-g6037357.zip






Online View Source: Https://github.com/mongodb/mongo-java-driver






2. Build a Javaproject project below and import the downloaded driver package. You can use MongoDB in Java with the following directory:










Second, Java operation MongoDB Example



Before this example you need to start the Mongod.exe service, the following program can be executed successfully after startup;












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






Mongo Mongo = new Mongo ();






This creates a MongoDB database connection object, which is connected by default to the current machine's localhost address, and the port is 27017.






DB db = Mongo.getdb ("test");






This will get a test database, if MongoDB does not create this database can also run normally. If you read the previous article, you know that MongoDB can do the data addition without creating the database. When added, without this library, MongoDB will automatically create the current database.






Get the db, next we want to get a "aggregation set dbcollection", through the DB object GetCollection method to complete.






Dbcollection users = db.getcollection ("users");






This gives you a dbcollection, which is equivalent to the "table" of our database.






Querying all data






Dbcursor cur = users.find ();






while (Cur.hasnext ()) {






System.out.println (Cur.next ());






}












Full source




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.MongoException;


Import Com.mongodb.util.JSON;



/**


* <b>function:</b>mongodb Simple Example


* @author Hoojo


* @createDate 2011-5-24 02:42:29


* @file Simpletest.java


* @package Com.hoo.test


* @project MongoDB


* @blog Http://blog.csdn.net/IBM_hoojo


* @email [email protected]


* @version 1.0


*/


public class SimpleTest {



   public static void Main (string[] args) throws Unknownhostexception, Mongoexception {


       Mongo mg = new Mongo ();


       Query all the database


       For (String name:mg.getDatabaseNames ()) {


           System.out.println ("DbName:" + name);


       }


       


       DB db = Mg.getdb ("test");


       Querying all the aggregation collections


       For (String name:db.getCollectionNames ()) {


           System.out.println ("CollectionName:" + name);


       }


       


       Dbcollection users = db.getcollection ("users");


       


       Querying all the 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, complete the crud operation, first set up a 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.MongoException;


Import com.mongodb.QueryOperators;


Import Com.mongodb.util.JSON;



/**


* <b>function:</b> to implement MONGODB CRUD operations


* @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 [email protected]


* @version 1.0


*/


public class Mongodb4crudtest {


   


   Private Mongo mg = null;


   private DB DB;


   Private dbcollection users;


   


   @Before


   public void init () {


       try {


           MG = new Mongo ();


           MG = new Mongo ("localhost", 27017);


       } catch (Unknownhostexception e) {


           E.printstacktrace ();


       } catch (Mongoexception e) {


           E.printstacktrace ();


       }


       Gets the temp DB; if not created by default, MongoDB automatically creates


       db = Mg.getdb ("temp");


       Get users dbcollection; if not created by default, MongoDB will automatically create


       Users = Db.getcollection ("users");


   }


   


   @After


   public void Destory () {


       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 the operation, we need to write a query method to query all the data. The code is as follows:




/**


* <b>function:</b> Search all data


* @author Hoojo


* @createDate 2011-6-2 03:22:40


*/


private void Queryall () {


   Print ("Query all data from users:");


   DB cursors


   Dbcursor cur = users.find ();


   while (Cur.hasnext ()) {


       Print (Cur.next ());


   }


}



@Test


public void Add () {


   Query all data First


   Queryall ();


   Print ("Count:" + users.count ());


   


   DBObject user = new Basicdbobject ();


   User.put ("name", "Hoojo");


   User.put ("Age", 24);


   Users.save (user) Save, GETN () Gets the number of rows affected


   Print (Users.save (user). GETN ());


   


   Expand Fields, add fields as you wish, without affecting existing data


   User.put ("Sex", "male");


   Print (Users.save (user). GETN ());


   


   Add multiple data, pass array object


   Print (Users.insert (user, new Basicdbobject ("name", "Tom")). GETN ());


   


   Add List Collection


   list<dbobject> list = new arraylist<dbobject> ();


   List.add (user);


   DBObject user2 = new Basicdbobject ("name", "Lucy");


   User.put ("Age", 22);


   List.add (User2);


   Add List Collection


   Print (Users.insert (list). GETN ());


   


   Query the data to see if the add succeeds


   Print ("Count:" + users.count ());


   Queryall ();


}










4. Delete data




@Test


public void Remove () {


   Queryall ();


   Print ("Delete id = 4de73f7acd812d61b4626a77:" + users.remove (New Basicdbobject ("_id", New ObjectId (" 4de73f7acd812d61b4626a77 ")). GETN ());


   Print ("Remove Age >=:" + users.remove (New Basicdbobject (' age ', New Basicdbobject ("$gte")). GETN ());


}










5. Modify the data




@Test


public void Modify () {


   Print ("Modify:" + users.update (New Basicdbobject ("_id", New ObjectId ("4dde25d06be7c53ffbd70906")), New Basicdbobject ("Age ). GETN ());


   Print ("Modify:" + users.update (


           


           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", "Dingding"),


           true,//If the database does not exist, whether to add


           True//false only change the first day, true if there are more than one, do not modify


           ). GETN ());


   


   Do not modify or add data when the database does not exist, when multiple data is not modified


   Print ("Modify multiple:" + coll.updatemulti (New Basicdbobject ("_id", New ObjectId ("4dde23616be7c19df07db42c"), new Basicdbobject ("Name", "199"));


}










6. Query data




@Test


public 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 =:" + users.find (New Basicdbobject ("Age",)). ToArray ());


   


   Query Age >= 24


   Print ("Find age >=:" + users.find (New Basicdbobject ("Age", New Basicdbobject ("$gte")). ToArray ());


   Print ("Find age <=:" + users.find (New Basicdbobject ("Age", New Basicdbobject ("$lte")). ToArray ());


   


   Print ("Query age!=25:" + users.find (New Basicdbobject ("Age", New Basicdbobject ("$ne")). ToArray ());


   Print ("Query age in 25/26/27:" + users.find (New Basicdbobject ("Age", New Basicdbobject (queryoperators.in, new int[] {25, 26, )). ToArray ());


   Print ("Query age not in 25/26/27:" + users.find (New Basicdbobject ("Age", New Basicdbobject (Queryoperators.nin, new int[] {25, )). ToArray ());


   Print ("Query Age exists sort:" + users.find (New Basicdbobject ("Age", New Basicdbobject (Queryoperators.exists, True)). ToArray ());


   


   Print ("Query only Age Property:" + Users.find (null, New Basicdbobject ("Age", true)). ToArray ());


   Print ("Check properties only:" + users.find (null, New Basicdbobject ("Age", true), 0, 2). ToArray ());


   Print ("Check properties only:" + users.find (null, New Basicdbobject ("Age", true), 0, 2, bytes.queryoption_notimeout). ToArray ());


   


   Query only one piece of data, multiple to the first


   Print ("FindOne:" + users.findone ());


   Print ("FindOne:" + users.findone (New Basicdbobject ("Age", 26));


   Print ("FindOne:" + users.findone (New Basicdbobject ("Age", "page"), New Basicdbobject ("name", true));


   


   Query modification, deletion


   Print ("Findandremove query age=25 data, and delete:" + users.findandremove (New Basicdbobject ("Age", 25));


   


   Query the age=26 data, and modify the value of name to ABC


   Print ("findandmodify:" + users.findandmodify ("New Basicdbobject" ("Age", "page"), New Basicdbobject ("name", "ABC"));


   Print ("findandmodify:" + users.findandmodify (


       New Basicdbobject ("Age", 28),//Querying age=28 data


       New Basicdbobject ("name", true),//Query the Name property


       New Basicdbobject ("Age", true),//Sort by age


       False,//Whether Delete, true means delete


       New Basicdbobject ("name", "ABC"),//modified value, change name to ABC


       


       true));


   


   Queryall ();


}




MongoDB does not support federated queries, subqueries, which need to be done by ourselves in the program. The result set of the query is filtered in the Java query as needed.












7. Other operations




public void Testothers () {


   DBObject user = new Basicdbobject ();


   User.put ("name", "Hoojo");


   User.put ("Age", 24);


   


   JSON Object Transformation        


   Print ("Serialize:" + json.serialize (user));


   Deserialization


   Print ("Parse:" + json.parse ("{\" name\ ": \" hoojo\ ", \" age\ ": 24}"));


   


   Print ("Determine if temp collection exists:" + db.collectionexists ("temp"));


   


   If it does not exist, 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 DB to read-only


   Db.setreadonly (TRUE);


   


   Read-only cannot write data


   Db.getcollection ("Test"). Save (user);


}

This article transferred from: http://www.cnblogs.com/hoojo/archive/2011/06/02/2068665.html




"MongoDB for Java" Java Operation MongoDB




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.