search
HomeJavajavaTutorialCode sharing of MongoDB usage guide in Java

MongoDB is a very popular NoSQL database today. This article introduces how to use MongoDB's Java driver to operate MongoDB.

1. Introduce the 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.

For detailed information on how to introduce the MongoDB jar package, please refer to the official documentation.

2. Connect to 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");

above The code connects to the MongoDB service on localhost:27017 and specifies to use 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 a multi-process environment. 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.

3. Authentication

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

1. Method 1: The

createCredential

method of the MongoCredentialMongoCredential class can specify the authentication user name, password, and database used, and Returns a MongoCredentialobject. The method is declared 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 user name user, password password, and database mydb.

The generated MongoCredential object will be used as the parameter of the MongoClient constructor function. Since the MongoClient constructor is of <a href="http://www.php.cn/wiki/1059.html" target="_blank">List</a><mongocredential></mongocredential> type, 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");

2. 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 MongoClientThe parameters of the 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");

4. Obtain a collection

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

Then you can operate on the specified collection, for example, insert, Delete , search, update documents, etc.

5. Insert document

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

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

now needs to be inserted into the collection mycol. To insert into a collection, a document can be constructed using BasicDB<a href="http://www.php.cn/wiki/60.html" target="_blank">Object</a>.

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

6. Find documents

1. Find a document that meets the conditions through findOne

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

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

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

2. Find all documents that meet the conditions through find

find is used to find documents that meet the conditions. It returns a DBCursor object, through Traverse the DBCursor object to obtain all documents that meet the search conditions.
For explanation 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));
}

findUsage examples are as follows:

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

will Output all documents in the mycol collection.

You can also specify the 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 conditions include $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();
}

7. Update the document

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

The above statement updates the document with i=70 to the value of i equal to 100.

与我们常用的更新文档的mongo语句一样,DBCollection还包含了savefindAndModify等更新文档的方法,其使用方法在此不再赘述,可以参考API说明文档即可。

八、删除文档

可以通过生成一个DBObject对象来删除指定的文档,例如:

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

上面的语句删除i为71的文档。

The above is the detailed content of Code sharing of MongoDB usage guide in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor