Updated on 2023-09-05 GMT+08:00

Accessing a Database

Before accessing a database, import the following classes:

import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import static com.mongodb.client.model.Filters.*;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.ValidationOptions;

Accessing DataBase

If an initialized MongoClient instance exists, run the following command to access a database:

MongoDatabase database = mongoClient.getDatabase("test");

Assessing a Collection

After obtaining a MongoDatabase instance, run the following command to obtain a collection:

MongoCollection<Document> coll = database.getCollection("testCollection");

Creating a Collection

You can use the createCollection() method to create a collection and specify the attributes of the collection.

database.createCollection("testCollection", new CreateCollectionOptions()..sizeInBytes(200000))

Inserting Data

Document doc0 = new Document("name", "zhangsan")       
               .append("age", 3)
               .append("sex", "male");

Document doc1 = new Document("name", "LiSi")
               .append("age", 2)
               .append("sex", "female");

Document doc2 = new Document("name", "wangmazi")
               .append("age", 5)
               .append("sex", "male");

List<Document> documents = new ArrayList<Document>();
documents.add(doc1);
documents.add(doc2);

collection.insertMany(documents);

Deleting Data

collection.deleteOne(eq("_id", new ObjectId("00000001")));

Deleting a Table

MongoCollection<Document> collection = database.getCollection("test");
collection.drop()

Reading Data

MongoCollection<Document> collection = database.getCollection("contacts");
MongoCursor<String> cursor = collection.find(); 
while (cursor.hasNext())  {
   Object result = cursor.next(); 
}

Query with Filter Criteria

MongoCollection<Document> collection = database.getCollection("test");
MongoCursor<String> cursor = collection.find(
    new Document("name","zhangsan")
          .append("age: 5));
while (cursor.hasNext())  {
   Object result = cursor.next(); 
}

Running Commands

Run buildInfo and collStats.

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("test");

Document buildInfoResults = database.runCommand(new Document("buildInfo", 1));
System.out.println(buildInfoResults.toJson());

Document collStatsResults = database.runCommand(new Document("collStats", "restaurants"));
System.out.println(collStatsResults.toJson());

Creating an Index

MongoClient mongoClient = MongoClients.create();
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("test");
collection.createIndex(Indexes.ascending("age"));