Docs Menu
Docs Home
/ / /
Java Reactive Streams Driver

Write Data to MongoDB

On this page

  • Overview
  • Insert One
  • Insert Multiple
  • Update One
  • Update Multiple
  • Replace One
  • Delete One
  • Delete Multiple
  • Bulk Write

This page contains copyable code examples of Java Reactive Streams driver methods that you can use to write data to MongoDB.

Tip

To learn more about any of the methods shown on this page, see the link provided in each section.

To use an example from this page, copy the code example into the sample application or your own application. Be sure to replace all placeholders in the code examples, such as <connection string>, with the relevant values for your MongoDB deployment.

This guide uses the Project Reactor library to consume Publisher instances returned by the Java Reactive Streams driver methods. To learn more about the Project Reactor library and how to use it, see Getting Started in the Reactor documentation.

There are also other ways to consume Publisher instances. You can use one of many alternative libraries such as RxJava or call Publisher.subscribe() directly and pass your own implementation of a Subscriber.

This guide uses the Mono.block() method from Reactor to subscribe to a Publisher and block the current thread until the Publisher reaches its terminal state. To learn more about the Reactive Streams initiative, see Reactive Streams.

Important

Publishers Returned are Cold

All Publisher instances returned by the Java Reactive Streams driver methods are cold, which means that the corresponding operation does not happen unless you subscribe to the returned Publisher. We recommend only subscribing to the returned Publisher once, because subscribing more than once can lead to errors.

You can use the following sample application to test the code examples on this page. To use the sample application, perform the following steps:

  1. Create a new Java project in your IDE.

  2. Install the Java Reactive Streams driver in your Java project.

  3. Install the Project Reactor library in your Java project.

  4. Copy the following code and paste it into a new Java file named WriteOperations.java.

  5. Copy a code example from this page and paste it on the specified lines in the file.

1import com.mongodb.MongoException;
2import com.mongodb.ConnectionString;
3import com.mongodb.MongoClientSettings;
4import com.mongodb.ServerApi;
5import com.mongodb.ServerApiVersion;
6import com.mongodb.bulk.BulkWriteResult;
7
8import com.mongodb.client.model.DeleteOneModel;
9import com.mongodb.client.model.InsertOneModel;
10import com.mongodb.client.model.ReplaceOneModel;
11import com.mongodb.client.model.UpdateOneModel;
12import com.mongodb.client.model.DeleteOptions;
13import com.mongodb.client.model.InsertManyOptions;
14import com.mongodb.client.model.InsertOneOptions;
15import com.mongodb.client.model.UpdateOptions;
16import com.mongodb.client.model.Updates;
17import com.mongodb.client.result.UpdateResult;
18import com.mongodb.client.result.DeleteResult;
19import com.mongodb.client.result.InsertManyResult;
20import com.mongodb.client.result.InsertOneResult;
21import com.mongodb.reactivestreams.client.MongoCollection;
22
23import org.bson.Document;
24
25import com.mongodb.reactivestreams.client.MongoClient;
26import com.mongodb.reactivestreams.client.MongoClients;
27import com.mongodb.reactivestreams.client.MongoDatabase;
28import reactor.core.publisher.Mono;
29
30import java.util.ArrayList;
31import java.util.Arrays;
32import java.util.List;
33
34import static com.mongodb.client.model.Filters.eq;
35import static com.mongodb.client.model.Updates.set;
36
37class WriteOperations {
38 public static void main(String[] args) throws InterruptedException {
39 // Replace the placeholder with your Atlas connection string
40 String uri = "<connection string>";
41
42 // Construct a ServerApi instance using the ServerApi.builder() method
43 ServerApi serverApi = ServerApi.builder()
44 .version(ServerApiVersion.V1)
45 .build();
46
47 MongoClientSettings settings = MongoClientSettings.builder()
48 .applyConnectionString(new ConnectionString(uri))
49 .serverApi(serverApi)
50 .build();
51
52 // Create a new client and connect to the server
53 try (MongoClient mongoClient = MongoClients.create(settings)) {
54 MongoDatabase database = mongoClient.getDatabase("<database name>");
55 MongoCollection<Document> collection = database.getCollection("<collection name>");
56 // Start example code here
57
58 // End example code here
59 }
60 }
61}
Document document = new Document("<field name>", "<value>");
Publisher<InsertOneResult> insertOnePublisher = collection.insertOne(document);
InsertOneResult result = Mono.from(insertOnePublisher).block();
System.out.printf("Inserted 1 document with ID %s.",
result.getInsertedId());

To learn more about the insertOne() method, see the Insert Documents guide.

Document doc1 = new Document("<field name>", "<value>");
Document doc2 = new Document("<field name>", "<value>");
List<Document> documents = Arrays.asList(doc1, doc2);
Publisher<InsertManyResult> insertManyPublisher = collection.insertMany(documents);
InsertManyResult result = Mono.from(insertManyPublisher).block();
System.out.printf("Inserted documents with IDs %s.",
result.getInsertedIds());

To learn more about the insertMany() method, see the Insert Documents guide.

Publisher<UpdateResult> updateOnePublisher = collection.updateOne(
eq("<field name>", "<value>"),
set("<field name>", "<new value>"));
UpdateResult result = Mono.from(updateOnePublisher).block();
System.out.printf("Updated %s document.",
result.getModifiedCount());

To learn more about the updateOne() method, see the Update Documents guide.

Publisher<UpdateResult> updateManyPublisher = collection.updateMany(
eq("<field name>", "<value>"),
set("<field name>", "<new value>"));
UpdateResult result = Mono.from(updateManyPublisher).block();
System.out.printf("Updated %s documents.",
result.getModifiedCount());

To learn more about the updateMany() method, see the Update Documents guide.

Publisher<UpdateResult> replaceOnePublisher = collection.replaceOne(
eq("<field name>", "<value>"),
new Document().append("<field name>", "<new value>")
.append("<new field name>", "<new value>"));
UpdateResult result = Mono.from(replaceOnePublisher).block();
System.out.printf("Replaced %s document.",
result.getModifiedCount());

To learn more about the replaceOne() method, see the Replace Documents guide.

Publisher<DeleteResult> deleteOnePublisher = collection.deleteOne(
eq("<field name>", "<value>"));
DeleteResult result = Mono.from(deleteOnePublisher).block();
System.out.printf("Deleted %s document.", result.getDeletedCount());

To learn more about the deleteOne() method, see the Delete Documents guide.

Publisher<DeleteResult> deleteManyPublisher = collection.deleteMany(
eq("<field name>", "<value>"));
DeleteResult result = Mono.from(deleteManyPublisher).block();
System.out.printf("Deleted %s documents.", result.getDeletedCount());

To learn more about the deleteMany() method, see the Delete Documents guide.

Publisher<BulkWriteResult> bulkWritePublisher = collection.bulkWrite(
Arrays.asList(new InsertOneModel<>(
new Document("<field name>", "<value>")),
new InsertOneModel<>(new Document("<field name>", "<value>")),
new UpdateOneModel<>(eq("<field name>", "<value>"),
set("<field name>", "<new value>")),
new DeleteOneModel<>(eq("<field name>", "<value>")),
new ReplaceOneModel<>(eq("<field name>", "<value>"),
new Document("<field name>", "<new value>")
.append("<new field name>", "<new value>"))));
BulkWriteResult bulkResult = Mono.from(bulkWritePublisher).block();
System.out.printf("Modified %s documents and deleted %s documents.",
bulkResult.getModifiedCount(), bulkResult.getDeletedCount());

Back

Databases and Collections