Write Data to MongoDB
On this page
Overview
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:
Create a new Java project in your IDE.
Install the Java Reactive Streams driver in your Java project.
Install the Project Reactor library in your Java project.
Copy the following code and paste it into a new Java file named
WriteOperations.java
.Copy a code example from this page and paste it on the specified lines in the file.
1 import com.mongodb.MongoException; 2 import com.mongodb.ConnectionString; 3 import com.mongodb.MongoClientSettings; 4 import com.mongodb.ServerApi; 5 import com.mongodb.ServerApiVersion; 6 import com.mongodb.bulk.BulkWriteResult; 7 8 import com.mongodb.client.model.DeleteOneModel; 9 import com.mongodb.client.model.InsertOneModel; 10 import com.mongodb.client.model.ReplaceOneModel; 11 import com.mongodb.client.model.UpdateOneModel; 12 import com.mongodb.client.model.DeleteOptions; 13 import com.mongodb.client.model.InsertManyOptions; 14 import com.mongodb.client.model.InsertOneOptions; 15 import com.mongodb.client.model.UpdateOptions; 16 import com.mongodb.client.model.Updates; 17 import com.mongodb.client.result.UpdateResult; 18 import com.mongodb.client.result.DeleteResult; 19 import com.mongodb.client.result.InsertManyResult; 20 import com.mongodb.client.result.InsertOneResult; 21 import com.mongodb.reactivestreams.client.MongoCollection; 22 23 import org.bson.Document; 24 25 import com.mongodb.reactivestreams.client.MongoClient; 26 import com.mongodb.reactivestreams.client.MongoClients; 27 import com.mongodb.reactivestreams.client.MongoDatabase; 28 import reactor.core.publisher.Mono; 29 30 import java.util.ArrayList; 31 import java.util.Arrays; 32 import java.util.List; 33 34 import static com.mongodb.client.model.Filters.eq; 35 import static com.mongodb.client.model.Updates.set; 36 37 class 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 }
Insert One
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.
Insert Multiple
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.
Update One
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.
Update Multiple
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.
Replace One
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.
Delete One
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.
Delete Multiple
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.
Bulk Write
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());