Docs Menu
Docs Home
/ / /
Java Reactive Streams Driver
/

Write Operations

On this page

  • Prerequisites
  • Connect to a MongoDB Deployment
  • Insert a Document
  • Insert Multiple Documents
  • Update Existing Documents
  • Filters
  • Update Operators
  • Update a Single Document
  • Update Multiple Documents
  • Update Options
  • Replace an Existing Document
  • Filters
  • Replace a Document
  • Update Options
  • Delete Documents
  • Filters
  • Delete a Single Document
  • Delete Multiple Documents
  • Write Concern

You can perform write operations to insert new documents, update existing documents, replace an existing document, or delete existing documents from a collection.

You must set up the following components to run the code examples in this guide:

  • A test.restaurants collection populated with documents from the restaurants.json file in the documentation assets GitHub.

  • 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 static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Updates.*;
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;

Important

This guide uses the Subscriber implementations, which are described in the Quick Start Primer.

First, connect to a MongoDB deployment, then declare and define MongoDatabase and MongoCollection instances.

The following code connects to a standalone MongoDB deployment running on localhost on port 27017. Then, it defines the database variable to refer to the test database and the collection variable to refer to the restaurants collection:

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

To learn more about connecting to MongoDB deployments, see the Connect to MongoDB tutorial.

To insert a single document into the collection, you can use the collection's insertOne() method:

Document document = new Document("name", "Café Con Leche")
.append("contact", new Document("phone", "228-555-0149")
.append("email", "cafeconleche@example.com")
.append("location",Arrays.asList(-73.92502, 40.8279556)))
.append("stars", 3)
.append("categories", Arrays.asList("Bakery", "Coffee", "Pastries"));
collection.insertOne(document).subscribe(new ObservableSubscriber<Void>());

Note

If no top-level id field is specified in the document, MongoDB automatically generates a value and adds this field to the inserted document.

To insert multiple documents, you can use the collection's insertMany() method, which takes a list of documents to insert as a parameter.

The following example inserts two documents into the collection:

Document doc1 = new Document("name", "Amarcord Pizzeria")
.append("contact", new Document("phone", "264-555-0193")
.append("email", "amarcord.pizzeria@example.net")
.append("location",Arrays.asList(-73.88502, 40.749556)))
.append("stars", 2)
.append("categories", Arrays.asList("Pizzeria", "Italian", "Pasta"));
Document doc2 = new Document("name", "Blue Coffee Bar")
.append("contact", new Document("phone", "604-555-0102")
.append("email", "bluecoffeebar@example.com")
.append("location",Arrays.asList(-73.97902, 40.8479556)))
.append("stars", 5)
.append("categories", Arrays.asList("Coffee", "Pastries"));
List<Document> documents = new ArrayList<Document>();
documents.add(doc1);
documents.add(doc2);
collection.insertMany(documents).subscribe(new ObservableSubscriber<Void>());;

Note

If no top-level id field is specified in the document, MongoDB automatically generates a value and adds this field to the inserted document.

To update existing documents in a collection, you can use the collection's updateOne() or updateMany() methods.

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. To facilitate the creation of filter objects, the driver provides the Filters helper class.

To specify an empty filter and match all documents in a collection, use an empty Document object as the filter.

To change a field in a document, MongoDB provides update operators. To specify the modification to perform using the update operators, create an update document. To learn more about update operators, see Update Operators in the Server manual.

To facilitate the creation of update documents, the driver provides the Updates helper class.

Important

The id field is immutable, so you cannot change the value of the id field in a document.

The updateOne() method updates a single document, even if the filter condition matches multiple documents in the collection.

The following operation on the restaurants collection updates a document in which the value of the id field is ObjectId("57506d62f57802807471dd41"):

collection.updateOne(
eq("_id", new ObjectId("57506d62f57802807471dd41")),
combine(set("stars", 1), set("contact.phone", "228-555-9999"), currentDate("lastModified"))
).subscribe(new ObservableSubscriber<UpdateResult>());

Specifically, the operation uses the following methods:

  • Updates.set() to set the value of the stars field to 1 and the contact.phone field to "228-555-9999"

  • Updates.currentDate() to modify the lastModified field to the current date. If the lastModified field does not exist, the operator adds the field to the document.

The updateMany() method updates all documents that match the filter condition.

The following operation on the restaurants collection updates all documents in which the value of the stars field is 2:

collection.updateMany(
eq("stars", 2),
combine(set("stars", 0), currentDate("lastModified"))
).subscribe(new ObservableSubscriber<UpdateResult>());

Specifically, the operation uses the following methods:

  • Updates.set() to set the value of the stars field to 0

  • Updates.currentDate() to set the lastModified field to the current date. If the lastModified field does not exist, the operator adds the field to the document.

When using the updateOne() and updateMany() methods, you can include an UpdateOptions document to specify the upsert option or the bypassDocumentationValidation option:

collection.updateOne(
eq("_id", 1),
combine(set("name", "Fresh Breads and Tulips"), currentDate("lastModified")),
new UpdateOptions().upsert(true).bypassDocumentValidation(true)
).subscribe(new ObservableSubscriber<UpdateResult>());

To replace an existing document in a collection, you can use the collection's replaceOne() method.

Important

The id field is immutable, so you cannot replace the id field in a document.

You can pass in a filter document to the replaceOne() method to specify which document to replace. The filter document specification is the same as for read operations. To facilitate the creation of filter objects, the driver provides the Filters helper class.

To specify an empty filter and match all documents in a collection, use an empty Document object as the filter.

The replaceOne() method replaces at most a single document, even if the filter condition matches multiple documents in the collection.

To replace a document, pass a new document to the replaceOne() 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 in which the value of the id field is ObjectId("57506d62f57802807471dd41"):

collection.replaceOne(
eq("_id", new ObjectId("57506d62f57802807471dd41")),
new Document("name", "Green Salads Buffet")
.append("contact", "TBD")
.append("categories", Arrays.asList("Salads", "Health Foods", "Buffet"))
).subscribe(new ObservableSubscriber<UpdateResult>());

When using the replaceOne() method, you can include an UpdateOptions document to specify the upsert option or the bypassDocumentationValidation 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)
).subscribe(new ObservableSubscriber<UpdateResult>());

To delete documents in a collection, you can use the deleteOne() and deleteMany() methods.

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. To facilitate the creation of filter objects, the driver provides the Filters helper class.

To specify an empty filter and match all documents in a collection, use an empty Document object as the filter.

The deleteOne() 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 in which the value of the _id field is ObjectId("57506d62f57802807471dd41"):

collection
.deleteOne(eq("_id", new ObjectId("57506d62f57802807471dd41")))
.subscribe(new ObservableSubscriber<DeleteResult>());

The deleteMany() method deletes all documents that match the filter condition.

The following operation on the restaurants collection deletes all documents in which the value of the stars field is 4:

collection
.deleteMany(eq("stars", 4))
.subscribe(new ObservableSubscriber<DeleteResult>());

Write concern describes the level of acknowledgment requested from MongoDB for write operations.

You can configure a write concern at the following levels:

  • In a MongoClient in the following ways:

    • By creating a MongoClientSettings instance:

      MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
      .applyConnectionString(new ConnectionString("mongodb://host1,host2"))
      .writeConcern(WriteConcern.MAJORITY)
      .build());
    • By creating a ConnectionString instance:

      MongoClient mongoClient = MongoClients.create("mongodb://host1:27017,host2:27017/?w=majority");
  • In a MongoDatabase by using the withWriteConcern() method:

    MongoDatabase database = mongoClient.getDatabase("test").withWriteConcern(WriteConcern.MAJORITY);
  • In a MongoCollection by using the withWriteConcern() method:

    MongoCollection<Document> collection = database
    .getCollection("restaurants")
    .withWriteConcern(WriteConcern.MAJORITY);

MongoDatabase and MongoCollection instances are immutable. Calling withWriteConcern() on an existing MongoDatabase or MongoCollection instance returns a new instance and does not affect the instance on which the method is called.

In the following example, the collWithWriteConcern instance has the write concern of majority whereas the read preference of the collection is unaffected:

MongoCollection<Document> collWithWriteConcern = collection
.withWriteConcern(WriteConcern.MAJORITY);

You can build MongoClientSettings, MongoDatabase, or MongoCollection instances to include combinations of read concerns, read preferences, and write concerns.

For example, the following code sets all three at the collection level:

Collection = database.getCollection("restaurants")
.withReadPreference(ReadPreference.primary())
.withReadConcern(ReadConcern.MAJORITY)
.withWriteConcern(WriteConcern.MAJORITY);

Back

Client-Side Encryption

Next

Bulk Write Operations