Professional Documents
Culture Documents
/) Search docs
(https://github.com/mongodb/mongo-java-
driver/blob/master/docs/reference/content/driver/tutorials/perform-
write-operations.md)
Java Driver (/mongo-java-driver/4.1/driver/) Tutorials (/mongo-java-driver/4.1/driver/tutorials/) Write Operations
Prerequisites
The example below requires a restaurants collection in the test database. To create and populate
the collection, follow the directions in github (https://github.com/mongodb/docs-assets/tree/drivers).
Include the following import statements:
import com.mongodb.*;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.result.*;
import org.bson.Document;
import org.bson.types.ObjectId;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
collection.insertOne(document);
NOTE:
If no top-level _id field is specified in the document, the Java driver automatically adds the _id
field to the inserted document.
collection.insertMany(documents);
NOTE:
If no top-level _id field is specified in the documents, the Java driver automatically adds the _id
field to the inserted documents.
Filters
You can pass in a filter document to the methods to specify which documents to update. The filter
document specification is the same as for read operations (/mongo-java-
driver/4.1/driver/tutorials/perform-read-operations/). To facilitate creating filter objects, the Java driver
provides the Filters (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/client/model/Filters.html ) helper.
To specify an empty filter (i.e. match all documents in a collection), use an empty Document (/mongo-
java-driver/4.1/apidocs/bson/org/bson/Document.html ) object.
Update Operators
(/mongo-java-driver/4.1/../)
To change a field in a document, MongoDB provides update operators
Search docs
To facilitate the creation of updates documents, the Java driver provides the Updates (/mongo-java-
driver/4.1/apidocs/mongodb-driver-core/com/mongodb/client/model/Updates.html ) class.
IMPORTANT:
The _id field is immutable; i.e. you cannot change the value of the _id field.
The following operation on the restaurants collection updates a document whose _id field equals
ObjectId("57506d62f57802807471dd41") .
collection.updateOne(
eq("_id", new ObjectId("57506d62f57802807471dd41")),
combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModifi
Updates.set (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/client/model/Updates.html#set(java.lang.String,TItem) ) to set the value of the
stars field to 1 and the contact.phone field to "228-555-9999" , and
Updates.currentDate (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/client/model/Updates.html#currentDate(java.lang.String) ) to modify the
lastModified field to the current date. If the lastModified field does not exist, the operator adds
the field to the document.
TIP:
In some cases where you may need to update many fields in a document, it may be more efficient to
replace the document. See Replace a Document.
Update Multiple Documents
The (/mongo-java-driver/4.1/../)
updateMany (/mongo-java-driver/4.1/apidocs/mongodb-driver-
Search docs
sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,org.bson.conve
) method updates all documents that match the filter condition.
The following operation on the restaurants collection updates all documents whose stars field equals
2.
collection.updateMany(
eq("stars", 2),
combine(set("stars", 0), currentDate("lastModified")));
Updates.set (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/client/model/Updates.html#set(java.lang.String,TItem) ) to set the value of the
stars field to 0 , and
Updates.currentDate (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/client/model/Updates.html#currentDate(java.lang.String) ) to modify the
lastModified field to the current date. If the lastModified field does not exist, the operator adds
the field to the document.
Update Options
With the updateOne() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html#updateOne(org.bson.conversions.Bson,org.bson.conve
) ) and updateMany (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html#updateMany(org.bson.conversions.Bson,org.bson.conve
) methods, you can include an UpdateOptions (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/client/model/UpdateOptions.html ) document to specify the upsert
(http://docs.mongodb.org/manual/reference/method/db.collection.update/#upsert-option ) option or the
bypassDocumentationValidation (http://docs.mongodb.org/manual/core/document-validation/#bypass-
document-validation ) option.
collection.updateOne(
eq("_id", 1),
combine(set("name", "Fresh Breads and Tulips"), currentDate("lastModified")),
new UpdateOptions().upsert(true).bypassDocumentValidation(true));
sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument) )
method.
IMPORTANT:
The _id field is immutable; i.e. you cannot replace the _id field value.
Filters
You can pass in a filter document to the method to specify which document to replace. The filter
document specification is the same as for read operations (/mongo-java-
driver/4.1/driver/tutorials/perform-read-operations/). To facilitate creating filter objects, the Java driver
provides the Filters (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/client/model/Filters.html ) helper.
To specify an empty filter (i.e. match all documents in a collection), use an empty Document (/mongo-
java-driver/4.1/apidocs/bson/org/bson/Document.html ) object.
Replace a Document
To replace a document, pass a new document to the replaceOne (/mongo-java-
driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument) )
method.
IMPORTANT:
The replacement document can have different fields from the original document. In the replacement
document, you can omit the _id field since the _id field is immutable; however, if you do include
the _id field, you cannot specify a different value for the _id field.
The following operation on the restaurants collection replaces the document whose _id field equals
ObjectId("57506d62f57802807471dd41") .
(/mongo-java-driver/4.1/../)
collection.replaceOne( Search docs
eq("_id", new ObjectId("57506d62f57802807471dd41")),
new Document("name", "Green Salads Buffet")
.append("contact", "TBD")
.append("categories", Arrays.asList("Salads", "Health Foods", "Buffet")));
Update Options
With the replaceOne (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html#replaceOne(org.bson.conversions.Bson,TDocument) ),
you can include an UpdateOptions (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/client/model/UpdateOptions.html ) document to specify the upsert
(http://docs.mongodb.org/manual/reference/method/db.collection.update/#upsert-option ) option or the
bypassDocumentationValidation (http://docs.mongodb.org/manual/core/document-validation/#bypass-
document-validation ) option.
collection.replaceOne(
eq("name", "Orange Patisserie and Gelateria"),
new Document("stars", 5)
.append("contact", "TBD")
.append("categories", Arrays.asList("Cafe", "Pastries", "Ice Cream")),
new UpdateOptions().upsert(true).bypassDocumentValidation(true));
Delete Documents
To delete documents in a collection, you can use the deleteOne (/mongo-java-
driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson) ) and
deleteMany (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html#deleteMany(org.bson.conversions.Bson) ) methods.
Filters
You can pass in a filter document to the methods to specify which documents to delete. The filter
document specification is the same as for read operations (/mongo-java-
driver/4.1/driver/tutorials/perform-read-operations/). To facilitate creating filter objects, the Java driver
provides the Filters (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/client/model/Filters.html ) helper.
To specify an empty filter (i.e. match all documents in a collection), use an empty Document (/mongo-
java-driver/4.1/apidocs/bson/org/bson/Document.html ) object.
Delete a Single Document
The (/mongo-java-driver/4.1/../)
deleteOne (/mongo-java-driver/4.1/apidocs/mongodb-driver-
Search docs
sync/com/mongodb/client/MongoCollection.html#deleteOne(org.bson.conversions.Bson) ) method
deletes at most a single document, even if the filter condition matches multiple documents in the
collection.
The following operation on the restaurants collection deletes a document whose _id field equals
ObjectId("57506d62f57802807471dd41") .
The following operation on the restaurants collection deletes all documents whose stars field equals
4.
collection.deleteMany(eq("stars", 4));
Write Concern
Write concern (http://docs.mongodb.org/manual/reference/write-concern ) describes the level of
acknowledgement requested from MongoDB for write operations.
In a MongoClient() (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoClient.html )
Via MongoClientSettings (/mongo-java-driver/4.1/apidocs/mongodb-driver-
core/com/mongodb/MongoClientSettings.html ):
(/mongo-java-driver/4.1/../) Search docs
MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
.applyConnectionString(new ConnectionString("mon
.writeConcern(WriteConcern.MAJORITY)
.build());
In a MongoDatabase (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoDatabase.html ) via its withWriteConcern (/mongo-java-
driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoDatabase.html#withWriteConcern(com.mongodb.WriteConcern) )
method, as in the following example:
In a MongoCollection (/mongo-java-driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html ) via its withWriteConcern (/mongo-java-
driver/4.1/apidocs/mongodb-driver-
sync/com/mongodb/client/MongoCollection.html#withWriteConcern(com.mongodb.WriteConcern) )
method, as in the following example:
For example, in the following, the collWithWriteConcern instance has the write concern of majority
whereas the write concern of the collection is unaffected.
(/mongo-java-driver/4.1/../)
MongoCollection<Document> collWithWriteConcern = collection Search docs
.withWriteConcern(WriteConcern.MAJORITY);
For example, the following sets all three at the collection level:
collection = database.getCollection("restaurants")
.withReadPreference(ReadPreference.primary())
.withReadConcern(ReadConcern.MAJORITY)
.withWriteConcern(WriteConcern.MAJORITY);