"MongoDB for Java" Java Operation MongoDB
Development of products in order to finance, constantly revised, from the first version to now the latest version, and finally found that the company's development direction has changed, the original e-commerce into the VR content provider (no way, to others money, you have to follow the planning strategy of others to go). Originally this chapter will be put in the back to do the explanation, helpless, the department needs to do a training task, I would like to take the Java operation MongoDB as a training content, development environment and dependent jar as follows:
(1) Development environment:
System:windows
Ide:eclipse
database:mongodb2.6
maven:apache-maven-3.0.4
(2) Development of dependent libraries:
JavaEE7, Mongo-2.6.5.jar, Junit-4.11.jar
First, the preparatory work
1, first, download MongoDB support for Java driver package (I directly take maven download, the article finally I will also put the corresponding Mongo-2.6.5.jar upload.
Mongodbfor Java's API document address is: HTTP://API.MONGODB.ORG/JAVA/2.6.5/
MongoDB for Java related Operation instance code: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/
I'm creating a MAVEN project with the following POM files:
<span style= "FONT-SIZE:18PX;" ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" >< modelversion>4.0.0</modelversion><groupid>com.hth</groupid><artifactid>mongodb</ Artifactid><packaging>war</packaging><version>0.0.1-snapshot</version><name> MongoDB Maven webapp</name><url>http://maven.apache.org</url><dependencies>< Dependency><groupid>junit</groupid><artifactid>junit</artifactid><version> 4.11</version><scope>test</scope></dependency><dependency><groupid> org.mongodb</groupid><artifactid>mongo-java-driver</artifactid><version>2.6.5</ version></dependency></dependencies><build><finalname>mongodb</finalname>< /build></project></span>
If your development environment does not have a MAVEN environment installed, you can build a Javaproject project, import the MongoDB driver jar package, and use MongoDB in Java.
Second, Java Operation MongoDB Example
Before this example you need to start MongoDB service, after startup, the following program can be executed smoothly;
1, establish Mongodbdemo. Java, complete the simple MongoDB database operation
Mongomongo = 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 gives you a database of test (the default database for MongoDB), and it works well if you do not create this database in MongoDB. 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 the "table" of our database, called a collection in MongoDB.
Querying all data
Dbcursor cur = users.find ();
while (Cur.hasnext ()) {
System.out.println (Cur.next ());
}
Full source
<span style= "FONT-SIZE:18PX;" >package com.hth.mongodb;import java.net.unknownhostexception;import Java.util.iterator;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;/** * @ClassName: Mongodbdemo * @Description: TODO (MongoDB test) * @author Wangzhao Date February 11, 2015 PM 3:56:16 * */public class Mongodbdemo {public static void main (string[] args) throws unknownhostexception,mongoexception {Mongo Mongo = new Mongo ("192.168.26.190", 27017); for (String DbName: Mongo.getdatabasenames ()) {System.out.println ("db instance:" + DbName);} DB db = Mongo.getdb ("Dreamerkr"); for (String cName:db.getCollectionNames ()) {System.out.println ("Dreamerkr present collection:" + CName);} Dbcollection webInfo = db.getcollection ("Web_info");D bcursor dbcursor = Webinfo.find (); while (Dbcursor.hasnext ()) { SYSTEM.OUT.PRINTLN ("Each document data is:" + dbcursor.next ());} for (Iterator it = Dbcursor.iterator (); It.hasnext ();) {SysTEM.OUT.PRINTLN ("Each document data is:" + it.next ());} System.out.println ("Number of documents:" + dbcursor.count ()); System.out.println ("Serialization of this Document" +json.serialize (Dbcursor));}} </span>
2, complete the crud operation, first set up a Mongodbcrudtest.java, the basic test code is as follows:
<span style= "FONT-SIZE:18PX;" >package com.hth.mongodb;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.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;/** * @ClassName: Mongodbcrudtest * @Description: TODO (MongoDB test) * @author Wangzhao Date 2015 Year February 11 pm 5:56:16 * */public class Mongodbcrudtest {private Mongo mg = null; private DB DB; Private Dbcollection Webinfos; @Before public void Init () {try {mg = new Mongo ("192.168.26.190", 27017); } catch (Unknownhostexception e) {e.printstacktrace (); } catch (Mongoexception e) {e.printstacktrace (); }//Get DreaMerkr DB; If not created by default, MongoDB will automatically create db = Mg.getdb ("Dreamerkr"); Get Web_info dbcollection; if not created by default, MongoDB will automatically create Webinfos = Db.getcollection ("Web_info"); } @After public void Destory () {if (mg! = null) {mg.close (); } mg = null; db = null; Webinfos = null; public void print (Object o) {System.out.println (o); }/** * 1.QUERYALL (querying all data using MongoDB's API). */@Test public void Queryall () {print ("Query all data for Webinfos:"); DB cursor Dbcursor cur = webinfos.find (); while (Cur.hasnext ()) {print (Cur.next ()); }}/** * Add (Insert an object). */@Test public void AddObject () {//query all data First Queryall (); Print ("Count:" + webinfos.count ()); DBObject webInfo = new Basicdbobject (); Webinfo.put ("name", "Chasing the Dreamer"); Webinfo.put ("Address", "http://www.dReamerkr.com "); Webinfos.save (WebInfo) Save, GETN () Gets the number of rows affected by print (Webinfos.save (webInfo). GETN ()); Query the data below to see if a successful print was added ("Count:" + webinfos.count ()); Queryall (); }/** * Add (Insert a list). */@Test public void Addlist () {queryall (); Print ("Count:" + webinfos.count ()); DBObject webInfo = new Basicdbobject (); list<dbobject> list = new arraylist<dbobject> (); Webinfo.put ("name", "Chasing the Dreamer"); Webinfo.put ("Address", "http://www.dreamerkr.com"); Webinfo.put ("Age", 2); List.add (WebInfo); DBObject WebInfo2 = new Basicdbobject ("name", "Dreamer 2"); Webinfo2.put ("Address", "www.hth.tv"); Webinfo2.put ("Age", 1); List.add (WebInfo2); Webinfos.insert (list); Query the data below to see if a successful print is added ("Count:" + webinfos.count ()); Queryall (); }/** * Add (Insert an array). */@Test public void AddArray () {queryall (); Print ("Count:" + webinfos.count ()); DBObject webInfo = new Basicdbobject (); Webinfo.put ("name", "Chasing the Dreamer"); Webinfo.put ("Address", "http://www.dreamerkr.com"); Add multiple data, pass array object Webinfos.insert (WebInfo, New Basicdbobject ("Name", "Rain Hit Line")); Print ("Count:" + webinfos.count ()); Queryall (); }/** * * Remove (delete data). */@Test public void Remove () {Queryall (); Print ("Delete id = 54dc0cc3c50afa2987800aff:" + webinfos.remove (New Basicdbobject ("_id", New ObjectId ( "54dc0cc3c50afa2987800aff"))). GETN ()); Print ("Remove name = Dreamer 2:" + Webinfos. Remove (New Basicdbobject ("name", "Dreamer 2")). GETN ()); Print ("Remove aGE > 1: "+ Webinfos. Remove (New Basicdbobject (" Age ", New Basicdbobject (" $g T ", 1))). GETN ()); }/** * * Modify (Modify data). */@Test public void Modify () {Queryall (); Print ("Modify:" + webinfos.update (New Basicdbobject ("_id", New ObjectId ( "54dc0808c50a5945720b1724"), New Basicdbobject ("Name", "Rain (2 ")). GETN ()); Print ("Modify:" + webinfos.update ("New Basicdbobject" ("_id", New ObjectId ("54dc130fc50a1c2e75e2b060"), New Basicdbobj ECT ("age", 122), true,//if the database does not exist, whether to add false//false only modify the first one, the management API says true when it is deleted many, the test result is a number of data do not modify, feel very strange, know the friend, Please explain to me, thank you). GETN ()); When the database does not exist to modify, do not add data, when multiple data is not modified (common reason, know the friend, please explain to me, thank you) print ("Modify multiple:" + Webinfos.updatemulti ("n Ame "," Chasing Dreamers "), New Basicdbobject (" name ", "Chasing the Dreamer"). GETN ()); Queryall (); }/** * * Query (querying data). */@Test public void query () {//Query id = 54dc130fc50a1c2e75e2b05c Print ("Find id = 54dc130fc50a1 C2E75E2B05C: "+ webinfos.find (New Basicdbobject (" _id ", New ObjectId ( "54dc130fc50a1c2e75e2b05c"))). ToArray ()); Query age = 122 print ("Find age = 122:" + webinfos.find (New Basicdbobject ("Age", 122)). ToArray ()); Query Age >= 1 print ("Find >= 1:" + Webinfos. Find (New Basicdbobject ("Age", New Basicdbobject ("$gte", 1))). ToArray ()); Print ("Find Age <= 2:" + Webinfos. Find (New Basicdbobject ("Age", new B Asicdbobject ("$lte", 2))). ToArray ()); Print ("Query age!=3:" + webinfos.find (New Basicdbobject ("Age", new Ba Sicdbobject ("$ne", 3))). ToArray ()); Print ("Query age in 1/122:" + webinfos.find (New Basicdbobject ("Age", new Basi Cdbobject (queryoperators.in, new int[] {1, 122})). ToArray ()); Print ("Query age not in 1/2/122:" + webinfos.find (New Basicdbobject ("Age", NE W Basicdbobject (Queryoperators.nin, new int[] {1, 2, 122})) . ToArray ()); Print ("Query Age exists sort:" + webinfos.find (New Basicdbobject ("Age", new Bas Icdbobject (Queryoperators.exists, True))). ToArray ()); Print ("Query Age property only:"+ Webinfos.find (NULL, New Basicdbobject ("Age", true)). ToArray ()); Query only one piece of data, multiple go to the first print ("FindOne:" + webinfos.findone ()); Print ("FindOne:" + webinfos.findone (New Basicdbobject ("Age", 1)); Print ("FindOne:" + webinfos.findone (New Basicdbobject ("Age", 1), New Basi Cdbobject ("name", true)); Query Modify, delete print ("Findandremove query age=2 data, and delete:" + webinfos.findandremove (new Basicdbobject ( "Age", 2)); Query the age=1 data, and modify the value of name for good fairy print ("findandmodify:" + webinfos.findandmodify (new Basicdbobjec T ("Age", 1), New Basicdbobject ("name", "Good fairy Tale")); Queryall (); }}</span>
Well, here's basically a way to introduce so many Java operations to MongoDB. Other things need your own research. The above methods of operation MongoDB are some common methods, relatively simple. If there is any problem, can give me a message, thank you!
MONGDB Basic Learning (vii)--"MongoDB for Java" Java Operation MongoDB