Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversJava Sync

Quick Reference

This page shows the driver syntax for several MongoDB commands and links to their related reference and API documentation.

Command
Syntax
coll.find(Filters.eq("title", "Hamlet")).first();
coll.find(Filters.eq("year", 2005))
coll.insertOne(new Document("title", "Jackie Robinson"));
coll.insertMany(
Arrays.asList(
new Document("title", "Dangal").append("rating", "Not Rated"),
new Document("title", "The Boss Baby").append("rating", "PG")));
coll.updateOne(
Filters.eq("title", "Amadeus"),
Updates.set("imdb.rating", 9.5));
coll.updateMany(
Filters.eq("year", 2001),
Updates.inc("imdb.votes", 100));
Update an Array in a Document

coll.updateOne(
Filters.eq("title", "Cosmos"),
Updates.push("genres", "Educational"));
coll.replaceOne(
Filters.and(Filters.eq("name", "Deli Llama"), Filters.eq("address", "2 Nassau St")),
new Document("name", "Lord of the Wings").append("zipcode", 10001));
coll.deleteOne(Filters.eq("title", "Congo"));
coll.deleteMany(Filters.regex("title", "^Shark.*"));
coll.bulkWrite(
Arrays.asList(
new InsertOneModel<Document>(
new Document().append("title", "A New Movie").append("year", 2022)),
new DeleteManyModel<Document>(
Filters.lt("year", 1970))));
coll.watch(Arrays.asList(
Aggregates.match(Filters.gte("year", 2022))));
Access Data from a Cursor Iteratively

MongoCursor<Document> cursor = coll.find().cursor();
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
Access Results from a Query as an Array

List<Document> resultList = new ArrayList<Document>();
coll.find().into(resultList);
coll.countDocuments(Filters.eq("year", 2000));
List the Distinct Documents or Field Values
coll.distinct("year", Integer.class);
Limit the Number of Documents Retrieved

coll.find().limit(2);
Skip Retrieved Documents

coll.find(Filters.regex("title", "^Rocky")).skip(2);
Sort the Documents When Retrieving Them

coll.find().sort(Sorts.ascending("year"));
Project Document Fields When Retrieving Them

coll.find().projection(Projections.fields(
Projections.excludeId(),
Projections.include("year", "imdb")));
coll.createIndex(
Indexes.compoundIndex(
Indexes.ascending("title"),
Indexes.descending("year")));
// only searches fields with text indexes
coll.find(Filters.text("zissou"));
Install the Driver Dependency with Maven
pom.xml
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.5.1</version>
</dependency>
</dependencies>
Install the Driver Dependency with Gradle
build.gradle
dependencies {
implementation 'org.mongodb:mongodb-driver-sync:4.5.1'
}
←  Quick StartWhat's New →