Introducing the MongoDB Java driver package
If the Java project that needs to manipulate MongoDB is a MAVEN project, you can add the following configuration to the dependency.
< dependencies ; <dependency ; <groupid ; org.mongodb </groupid ; <artifactid ; mongo-java-driver </artifactid ; <version ; 2.13.2< /version ; </ Dependency ; </dependencies >
or by directly downloading the jar package: Mongo-java-driver-2.13.2.jar.
Connect to MongoDB
You can use it MongoClient
to connect to MongoDB MongoClient
using the following methods:
new MongoClient("localhost"27017);DB db = mongoClient.getDB("mydb");
The above code connects the localhost:27017 on the MongoDB service and specifies the use of the mydb database. This database can be further manipulated after the connection is made.
It should be noted that MongoClient
it is thread-safe and can share the same in both the multi-pass and the environment MongoClient
. Typically, in an application, you only need to generate a global MongoClient
instance, and then use that instance elsewhere in the program.
Certification
There are several ways to authenticate a connection, and here are two ways to do it.
Way One: mongocredential
MongoCredential
The method of the class createCredential
can specify the authenticated user name, password, and the database used, and returns an MongoCredential
object. The declaration of its method is as follows:
static MongoCredential createCredential(StringStringchar[] password)
For example
MongoCredential credential = MongoCredential.createCredential("user""mydb""password".toCharArray();
The
above creates a mongocredential object named user with a password of password and a database of mydb
. The
generates mongocredential
objects as parameters to the mongoclient
constructor. Because the mongoclient
constructor is of type list<mongocredential>
, it needs to be constructed into a List to be passed first. Examples of complete certifications are 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");
Way two: Mongoclienturi
You can also use the MongoClientURI
credentials to complete MongoDB, which represents a URI object. MongoClientURI
's constructor accepts a string of type strings, the format of which is as follows:
Mongodb://[username:[email protected]]host1[:p ort1][,host2[:p Ort2],... [, hostn[:p Ortn]] [/[database][?options]]
The resulting MongoClientURI
object is used as a MongoClient
constructor parameter, and 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");
You can then manipulate the specified collection, for example, insert, delete, find, update the document, and so on.
Insert Document
For example, a document is represented in JSON as follows,
{"Name": "MONGO", "info": {"ver": "3.0"}}
Now you need to insert into the collection MyCol . In order to insert into the collection, you can use the BasicDBObject
construct one document.
new BasicDBObject("name""mongo").append("info"new BasicDBObject("ver""3.0"));coll.insert(doc);
Find a document find a qualifying document by FindOne
findOne
you can find a document that matches your criteria. 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 findOne
find a document that matches the find criteria by specifying a lookup parameter.
Find all eligible documents through find
Find is used to look up a document that matches a condition, and it returns an DBCursor
object that DBCursor
can be traversed to get all the documents that match the search criteria.
To illustrate and test, we first insert a batch of documents in the following format
{"I": value}
fori=0i100i{ coll.insert(new BasicDBObject("i", i));}
Examples of use of find are as follows:
DBCursor cursor = coll.find();try { while(cursor.hasNext()) { System.out.println(cursor.next()); }} finally { cursor.close();}
All the documents in the MyCol collection are exported.
You can also specify criteria for the lookup, such as:
BasicDBObject query = new BasicDBObject("i"71);DBCursor cursor = coll.find(query);try { while(cursor.hasNext()) { System.out.println(cursor.next()); }} finally { cursor.close();}
For cases where the $ operator is included in the find condition, such as one of the following MONGO Shell commands:
Db.coll.find ({i: {$gte: 50}});
You can use DBObject
the build lookup criteria to
// find all where i >= 50new 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
new BasicDBObject("i"70new BasicDBObject("$set"new BasicDBObject("i"100));coll.update(query, up);
The above statement will update I for document I to 70 with a value equal to 100.
The same as the MONGO statement of the update document we commonly DBCollection
use, but also contains save
, and so on, the method of updating the document, findAndModify
its usage is not described here, you can refer to the API documentation.
Delete a document
You can DBObject
delete the specified document by generating an object, for example:
BasicDBObjectqueryBasicDBObject("i"71);coll.remove(query);
The above statement deletes the document I is 71.
Resources
- 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 NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
MongoDB Java Usage Guide