MongDB basic learning (7) -- [MongoDB for Java] Java operations on MongoDB and mongdbmongodb

Source: Internet
Author: User
Tags findone mongodb driver

MongDB basic learning (7) -- [MongoDB for Java] Java operations on MongoDB and mongdbmongodb

[MongoDB for Java] Java operations on MongoDB

The developed products are constantly revised for financing purposes. From the first version to the latest version, we finally found that the company's development direction has changed. In the beginning, e-commerce was changed to VR content providers (there is no way to ask others for money, you have to follow the strategy planned by others ). This section will be followed for further explanation. However, the Department needs to perform a training task and I want to use Java to operate MongoDB as the training content. The development environment and dependent jar are as follows:

(1) Development Environment:

System: Windows

IDE: eclipse

Database: mongoDB2.6

Maven: apache-maven-3.0.4

(2) Development dependent libraries:

JavaEE7, mongo-2.6.5.jar, junit-4.11.jar

I. Preparations

1. First, download the mongoDB driver package for Java support (I directly download maven, the article finally I will upload the corresponding mongo-2.6.5.jar.

MongoDBfor Java API documentation address: 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 created a Maven project. The pom file is as follows:

<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 the maven environment is not installed in your development environment, you can create a JavaProject project and import the MongoDB driver jar package to use mongoDB in Java,

Ii. Java MongoDB operation example

Before this example, you must start the mongoDB service. After it is started, the following program can be successfully executed;

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

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 (the default database of mongoDB) is obtained. If this database is not created in mongoDB, it can run normally. 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, we get a DBCollection, which is equivalent to the "table" of our database, which is called a collection in MongoDB.

Query all data

DBCursor cur = users. find ();

While (cur. hasNext ()){

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

}

Complete source code

<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. except exception; import com. mongodb. util. JSON;/*** @ ClassName: MongoDBDemo * @ Description: TODO (MongoDB test) * @ author wangzhao date February 11, 2015 3:56:16 **/public class MongoDBDemo {public static void main (String [] args) throws UnknownHostException, unknown exception {Mongo mongo = new Mongo ("192.168.26.190 ", 27017); for (String dbName: mongo. getDatabaseNames () {System. out. println ("database instance:" + dbName);} DB db = mongo. getDB ("dreamerkr"); for (String cName: db. getCollectionNames () {System. out. println ("collection of dreamerkr:" + cName);} DBCollection webInfo = db. getCollection ("web_info"); DBCursor 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 ("serialize this document" + JSON. serialize (dbCursor) ;}</span>

2. To complete the CRUD operation, first create 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. except exception; import com. mongodb. queryOperators;/*** @ ClassName: MongoDBCRUDTest * @ Description: TODO (MongoDB test) * @ author wangzhao date February 11, 2015 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 (except exception e) {e. printStackTrace ();} // obtain dreamerkr DB. If no database is created by default, mongodb automatically creates db = mg. getDB ("dreamerkr"); // get web_info DBCollection; if it is 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 (query all data using MongoDB APIs ). * // @ Test public void queryAll () {print ("query all webInfos data:"); // db cursor DBCursor cur = webInfos. find (); while (cur. hasNext () {print (cur. next () ;}}/*** add (insert an object ). * // @ Test public void addObject () {// first query all data queryAll (); print ("count:" + WebInfos. count (); DBObject webInfo = new BasicDBObject (); webInfo. put ("name", "dream catcher"); webInfo. put ("address", "http://www.dreamerkr.com"); // webInfos. save (webInfo) save, getN () Get the number of affected rows print (webInfos. save (webInfo ). getN (); // query the data to see if print ("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", "dream catcher"); webInfo. put ("address", "http://www.dreamerkr.com"); webInfo. put ("age", 2); list. add (webInfo); DBObject webInfo2 = new BasicDBObject ("name", "Dream chaser 2"); webInfo2.put ("address", "www. hth. TV "); webInfo2.put (" age ", 1); list. add (webInfo2); webInfos. insert (list); // query the data to see if print ("count:" + w EbInfos. count (); queryAll ();}/*** add (insert an array ). */@ Test public void addArray () {queryAll (); print ("count:" + webInfos. count (); DBObject webInfo = new BasicDBObject (); webInfo. put ("name", "dream catcher"); webInfo. put ("address", "http://www.dreamerkr.com"); // Add multiple pieces of data and pass the Array object webInfos. insert (webInfo, new BasicDBObject ("name", "Rain ranking"); 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 = Mengke 2:" + webInfos. remove (new BasicDBObject ("name", "Dream chaser 2 ")). getN (); print ("remove age> 1:" + webInfos. remove (new BasicDBObject ("age", new BasicDBObject ("$ gt", 1 ))). getN ());}/**** Modify (modify data ). */@ Test public void modify () {queryAll (); print ("modify:" + webInfos. update (new BasicDBObject ("_ id", new ObjectId ("54dc0808c50a5945720b1724"), new BasicDBObject ("name", "rain beat ranking 2 ")). getN (); print ("Modify:" + webInfos. update (new BasicDBObject ("_ id", new ObjectId ("54dc130fc50a1c2e75e2b060"), new BasicDBObject ("age", 122), true, // if the database does not exist, whether to add false // false. Only the first entry is modified. If the management api is set to true, multiple entries are deleted and the test result is multiple. I don't want to modify the data. It's strange. If you know me, please explain it to me. Thank you ). getN (); // when the database does not exist, it will not be modified or added, but it will not be modified when there are multiple data records (for general reasons, please explain to me, thank you) print ("Modify multiple:" + webInfos. updateMulti (new BasicDBObject ("name", "Dream Chaser"), new BasicDBObject ("name", "Dream Chaser ")). getN (); queryAll ();}/***** query (query data ). * // @ Test public void query () {// query id = 54dc130fc50a1c2e75e2b05c print ("find id = 54dc130fc50a1c2e75e2b05c:" + webInfos. find (new BasicDBObject ("_ id", n Ew ObjectId ("54dc130fc50a1c2e75e2b05c "))). toArray (); // query age = 122 print ("find age = 122:" + webInfos. find (new BasicDBObject ("age", 122 )). toArray (); // query age> = 1 print ("find age> = 1:" + webInfos. find (new BasicDBObject ("age", new BasicDBObject ("$ gte", 1 ))). toArray (); print ("find age <= 2:" + webInfos. find (new BasicDBObject ("age", new BasicDBObject ("$ lte", 2 ))). toArray (); print ("query age! = 3: "+ webInfos. find (new BasicDBObject ("age", new BasicDBObject ("$ ne", 3 ))). toArray (); print ("query age in 1/122:" + webInfos. find (new BasicDBObject ("age", new BasicDBObject (QueryOperators. IN, new int [] {1,122 }))). toArray (); print ("query age not in 1/2/122:" + webInfos. find (new BasicDBObject ("age", new BasicDBObject (QueryOperators. NIN, new int [] {1, 2,122 }))). toArray (); print ("query age exists sorting:" + webInfos. find (new BasicDBObject ("age", new BasicDBObject (QueryOperators. EXISTS, true ))). toArray (); print ("only query age attributes:" + webInfos. find (null, new BasicDBObject ("age", true )). toArray (); // query only one piece of data, multiple entries 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 BasicDBObject ("name", true ))); // query, modify, and delete print ("findAndRemove query age = 2 data, and delete:" + webInfos. findAndRemove (new BasicDBObject ("age", 2); // query the data with age = 1, and modify the name value as a fairy tale print ("findAndModify:" + webInfos. findAndModify (new BasicDBObject ("age", 1), new BasicDBObject ("name", "fairy tale"); queryAll () ;}</span>
Now, we will introduce so many Java operations on MongoDB. You need to study other things on your own. The above operations on MongoDB are common and relatively simple. If you have any questions, please leave a message. Thank you!

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.