Guidelines for using MongoDB in Java

Source: Internet
Author: User
Tags findone mongoclient mongo shell

First, the introduction of 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.

Detailed information on how to introduce MongoDB jar packages can be found in the official documentation.

Second, connect MongoDB

You can use it MongoClient to connect to MongoDB MongoClient using the following methods:

Mongoclient mongoclient = new Mongoclient ("localhost", 27017);D b 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 to share the same in a Cheng environment MongoClient . Typically, in an application, you only need to generate a global MongoClient instance, and then use that instance elsewhere in the program.

Third, certification

There are several ways to authenticate a connection, and here are two ways to do it.

1. Mode one: mongocredential

MongoCredentialThe 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 (string userName, String database, char[] password)

For example

Mongocredential credential = mongocredential.createcredential ("User", "mydb", "Password". ToCharArray ();

The above creates an object with a username of user, a password of password, and a database of MyDB MongoCredential .

The generated MongoCredential object is used as a MongoClient parameter to the constructor. Because MongoClient of the type of the constructor List<MongoCredential> , it needs to be constructed into a list and then passed. 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");
2. Mode 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:%[email protected]%s:%d/%s", "User", "password", "localhost", 27017, "mydb"); Mongoclienturi uri = new Mongoclienturi (SURI); Mongoclient mongoclient = new Mongoclient (URI); DB db = Mongoclient.getdb ("MyDB");
Iv. getting 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.

V. Inserting documents

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.

Basicdbobject doc = new Basicdbobject ("name", "MONGO"). Append ("Info", New Basicdbobject ("ver", "3.0")); Coll.insert (doc );
Six, find the document 1. Find a qualifying document by FindOne

findOneyou 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.

2. Find all eligible documents through find

findUsed to find a document that matches a condition, it returns an object that, DBCursor by traversing the DBCursor object, can 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}
for (int i=0; i <; i++) {    Coll.insert (new Basicdbobject ("I", I));}

findUse the following example:

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", ();D bcursor cursor = coll.find (query); try {while   (Cursor.hasnext ()) { C5/>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 >= 50BasicDBObject query = new Basicdbobject ("I", New Basicdbobject ("$gte",));D bcursor cursor = Coll.find (query); try {while    (Cursor.hasnext ()) {        System.out.println (Cursor.next ());}    } finally {    Cursor.close ();}
Vii. Updating documents
Basicdbobject query = new Basicdbobject ("I", 70); Basicdbobject up = new Basicdbobject ("$set", New Basicdbobject ("I", +)); 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.

Viii. Deleting documents

You can DBObject delete the specified document by generating an object, for example:

Basicdbobject query = new Basicdbobject ("I", +); coll.remove (query);

The above statement deletes the document I is 71.

Guidelines for using MongoDB in Java

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.