1024programmer Java MongoDBJava usage guide

MongoDBJava usage guide

Introduce MongoDB Java Driver package

If the Java project that needs to operate MongoDB is a Maven project, you can add the following configuration to the dependencies.

<dependencies>
     <dependency>
         <groupId>org.mongodb</groupId>
         <artifactId>mongo-java-driver</artifactId>
         <version>2.13.2</version>
     </dependency>
 </dependencies>

Or use it by directly downloading the jar package, download address: mongo-java-driver-2.13.2.jar.

Connect MongoDB

You can use MongoClient to connect to MongoDB. The usage of MongoClient is as follows:

MongoClient mOngoClient= new MongoClient(  "localhost", 27017);
 DB db = mongoClient.getDB("mydb");

The above code connects to the MongoDB service on localhost:27017 and specifies the use of the mydb database. After connecting, you can perform further operations on this database.
It should be pointed out that MongoClient is thread-safe and can share the same MongoClient in multiple processes and environments. Generally speaking, in an application, you only need to generate a global MongoClient instance, and then use this instance in other places in the program.

certification

You can use multiple methods to authenticate connections. Two methods are introduced below.

Method 1: MongoCredential

The createCredential method of the

MongoCredential class can specify the authenticated username, password, and database used, and returns a MongoCredential object. The declaration of its method is as follows:

static MongoCredential createCredential(String  userName, String database, char[] password)

For example,

MongoCredential credential = MongoCredential.createCredential("user  ", "mydb", "password".toCharArray();

The above creates a MongoCredential object with the username user, password password, and database mydb .
Use the object that generates MongoCredential as a parameter of the MongoClient constructor. Since the MongoClient constructor is of type List, it needs to be constructed into a List first and then passed. A complete authentication example is as follows:

MongoCredential credential = MongoCredential.createCredential("user", "mydb", "password".toCharArray()); 
 ServerAddress serverAddress = new ServerAddress("localhost", 27017)  ; 
 MongoClient mOngoClient= new MongoClient(serverAddress, Arrays.asList(credential)); 
 DB db = mongoClient.getDB("mydb");  

Method 2: MongoClientURI

You can also use MongoClientURI to complete MongoDB authentication, which represents a URI object. The constructor of MongoClientURI accepts a string of type String. The format of this string is as follows:

mongodb://[username:password@]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]]

The generated MongoClientURI object is used as a parameter of the MongoClient constructor. The complete authentication example is as follows:

String sURI = String.format("mongodb://%s:%s@  %s:%d/%s", "user", "password", "localhost",  27017, "mydb");
 MongoClientURI uri = new MongoClientURI(sURI);
 MongoClient mOngoClient= new MongoClient(uri);
 DB db = mongoClient.getDB("mydb");

Get a collection

DBCollection coll = db.getCollection("mycol  ");

Then you can perform operations on the specified collection, such as inserting, deleting, searching, updating documents, etc.

Insert document

For example, a document is represented as follows in Json,

{ “name”: “mongo”, “info”: { “ver”: “3.0” } }

Now it needs to be inserted into the collection mycol. To insert into a collection, a document can be constructed using BasicDBObject.

BasicDBObject doc = new BasicDBObject("name"  , "mongo").append(  "info", new BasicDBObject("ver", "3.0"));
 coll.insert(doc);

Find Document

Find a qualified document through findOne

You can find a document that meets the conditions through findOne. For example, for the mycol collection above, execute the following command:

DBObject myDoc = coll.findOne();  
 System.out.println(myDoc);

The first document in the mycol collection will be output. You can also find a document that meets the search conditions by specifying the search parameters of findOne.

Find all matching documents through find

find is used to find documents that meet the conditions. It returns a DBCursor object. By traversing the DBCursor object, you can obtain all documents that meet the search conditions.
For illustration and testing, we first insert a batch of documents in the following format

{ “i”: value }

for (int i=  0; i <100; i++) {
     coll.insert(new BasicDBObject("i", i));
 }

The usage examples of find are as follows:

DBCursor cursor = coll.find();  
 try {
    while(cursor.hasNext()) {
        System.out.println(cursor.next());
    }
 } finally {
    cursor.close();
 }

All documents in the mycol collection will be output.
You can also specify search conditions, for example:

BasicDBObject query = new BasicDBObject("i", 71);

 DBCursor cursor = coll.find(query);

 try {
    while(cursor.hasNext()) {
        System.out.println(cursor.next());
    }
 } finally {
    cursor.close();
 }

For the case where the search condition includes the $ operator, for example the following mongo shell command:

db.coll.find({i: {$gte: 50}});

You can use DBObject to generate search conditions,

// find all where i >= 50
 BasicDBObject query = new BasicDBObject("i", new BasicDBObject("$gte", 50));

 DBCursor cursor = coll.find(query);
 try {
     while (cursor.hasNext()) {
         System.out.println(cursor.next());
     }
 } finally {
     cursor.close();
 }

Update Document

BasicDBObject query = new BasicDBObject("i"  , 70);
 BasicDBObject up = new BasicDBObject("$set", new   BasicDBObject("i", 100));
 coll.update(query, up);

The above statement will update the document whose i is 70 to have the value of i equal to 100.
Like our commonly used mongo statements for updating documents, DBCollection also includes save, findAndModify and other methods for updating documents. How to use them is here No need to go into details, you can refer to the API documentation.

Delete document

The specified document can be deleted by generating a DBObject object, for example:

BasicDBObject query = new BasicDBObject("i", 71);
 coll.remove(query);

The above statement deletes documents with i equal to 71.

References

  • http://mongodb.github.io/mongo-java-driver/2.13/getting-started/installation-guide/
  • http://mongodb.github.io/mongo-java-driver/2.13/getting-started/quick-tour/
  • https://github.com/mongodb/mongo-java-driver/blob/2.13.x/src/examples/example/QuickTour.java
  • http://mongodb.github.io/mongo-java-driver/3.0/driver/reference/connecting/authenticating/
  • http://api.mongodb.org/java/3.0/?com/mongodb/MongoClientURI.html
  • http://api.mongodb.org/java/2.13/

Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger’s permission.

MongoDB Java User Guide



();
}

For the case where the search condition includes the $ operator, for example the following mongo shell command:

db.coll.find({i: {$gte: 50}});

You can use DBObject to generate search conditions,

// find all where i >= 50
 BasicDBObject query = new BasicDBObject("i", new BasicDBObject("$gte", 50));

 DBCursor cursor = coll.find(query);
 try {
     while (cursor.hasNext()) {
         System.out.println(cursor.next());
     }
 } finally {
     cursor.close();
 }

Update Document

BasicDBObject query = new BasicDBObject("i"  , 70);
 BasicDBObject up = new BasicDBObject("$set", new   BasicDBObject("i", 100));
 coll.update(query, up);

The above statement will update the document whose i is 70 to have the value of i equal to 100.
Like our commonly used mongo statements for updating documents, DBCollection also includes save, findAndModify and other methods for updating documents. How to use them is here No need to go into details, you can refer to the API documentation.

Delete document

The specified document can be deleted by generating a DBObject object, for example:

BasicDBObject query = new BasicDBObject("i", 71);
 coll.remove(query);

The above statement deletes documents with i equal to 71.

References

  • http://mongodb.github.io/mongo-java-driver/2.13/getting-started/installation-guide/
  • http://mongodb.github.io/mongo-java-driver/2.13/getting-started/quick-tour/
  • https://github.com/mongodb/mongo-java-driver/blob/2.13.x/src/examples/example/QuickTour.java
  • http://mongodb.github.io/mongo-java-driver/3.0/driver/reference/connecting/authenticating/
  • http://api.mongodb.org/java/3.0/?com/mongodb/MongoClientURI.html
  • http://api.mongodb.org/java/2.13/

Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger’s permission.

MongoDB Java User Guide


This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/772401

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索