Overview
In this guide, you can learn how to use the Java Reactive Streams driver to update documents in a MongoDB collection by performing update operations.
An update operation updates one or more documents in a MongoDB collection. You can perform an update operation by using the updateOne() or updateMany() methods.
Sample Data
The examples in this guide use the restaurants collection from the sample_restaurants database in the Atlas sample datasets.
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started tutorial.
Important
Project Reactor Library
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. To learn more about how we use Project Reactor library methods in this guide, see the Write Data to MongoDB guide.
Update Operations
You can perform update operations in MongoDB by using the following methods:
updateOne(), which updates the first document that matches the search criteriaupdateMany(), which updates all documents that match the search criteria
Each update method requires the following parameters:
Query filter document, which determines the documents to update. For more information about using query filters, see the Filters section.
Update document, which specifies the update operator (the kind of update to perform) and the fields and values to change. For more information about update operators, see the Update Operators section.
Filters
Each update method requires a query filter, which specifies the search criteria that determine which documents to select for updates. To facilitate the creation of filter objects, the driver provides the Filters class that provides filter condition helper methods.
To view a list of Filters helpers, see the Filters
API documentation. For more information about query filters, see the Query Filter Documents section in the MongoDB Server manual.
Update Operators
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 facilitate the creation of update documents, the driver provides the Updates helper class that contains filter condition helper methods.
Important
The _id field is immutable, so you cannot change the value of the _id field in a document.
To learn more about update operators, see Update Operators in the Server manual.
Update One Document
To update a single document in a MongoDB collection, call the updateOne() method and pass your query filter and update operators. Then, pass the updateOne() result to the static Mono.from() method from Mono. Mono is a class from the Project Reactor library. In Java Reactive Streams, the driver methods return cold Publisher instances, which means that the corresponding operation does not happen unless you subscribe to the returned Publisher. This guide uses the Project Reactor library to consume them. To learn more about Mono, see Mono in the Project Reactor documentation.
The following example uses the updateOne() method to update the name value of a matching document from "Bagels N Buns" to "2 Bagels 2 Buns":
Publisher<UpdateResult> updatePublisher = restaurants.updateOne(eq("name", "Bagels N Buns"), set("name", "2 Bagels 2 Buns")); Mono.from(updatePublisher).block();
Update Multiple Documents
To update multiple documents in a MongoDB collection, call the updateMany() method and pass your query filter and update operators. Then, pass the updateMany() result to the static Mono.from() method from Mono. Mono is a class from the Project Reactor library. In Java Reactive Streams, the driver methods return cold Publisher instances, which means that the corresponding operation does not happen unless you subscribe to the returned Publisher. This guide uses the Project Reactor library to consume them. To learn more about Mono, see Mono in the Project Reactor documentation.
The following example uses the updateMany() method to update all documents that have a cuisine value of "Pizza" to have a cuisine value of "Pasta":
Publisher<UpdateResult> updatePublisher = restaurants.updateMany(eq("cuisine", "Pizza"), set("cuisine", "Pasta")); Mono.from(updatePublisher).block();
Customize the Update Operation
The UpdateOptions class contains methods that modify the behavior of update methods. To use the UpdateOptions class, construct a new instance of the class, then call one or more of its methods to modify the update operation. You can chain these method calls together. To modify the behavior of the update operation, pass the class instance and chained method calls as the third argument to the updateOne() or updateMany() method.
You can use the following optional methods in the UpdateOptions class to modify an update operation:
Method | Description |
|---|---|
| Specifies which array elements an update applies to. |
| Specifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual. |
| Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual. |
| Attaches a |
| Attaches a |
| Sets the index for the operation as a |
| Sets the index for the operation as a |
| Specifies a map of parameter names and values. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual. |
| Sets the sort criteria to apply to the operation. If multiple
documents match the query filter that you pass to the
|
| Specifies whether the update operation performs an upsert operation if no documents match the query filter. For more information, see the upsert statement in the MongoDB Server manual. |
Upsert Example
An upsert operation updates documents that match your query filter and inserts a new document if there are no matches to your query filter.
The following code uses the updateMany() method to find all documents where the borough field has the value "Manhattan". It then updates the borough value in these documents to "Manhattan (north)". Because the upsert option is set to true, the Java Reactive Streams driver inserts a new document if the query filter doesn't match any existing documents. The example returns the number of documents that match the query filter and the number of documents modified by the upsert operation.
Bson filter = Filters.eq("borough", "Manhattan"); Bson update = Updates.set("borough", "Manhattan (north)"); UpdateOptions options = new UpdateOptions().upsert(true); Publisher<UpdateResult> updateManyPublisher = restaurants.updateMany(filter, update, options); UpdateResult result = Mono.from(updateManyPublisher).block(); System.out.println("Matched: " + result.getMatchedCount() + ", Modified: " + result.getModifiedCount() + ", Upserted ID: " + result.getUpsertedId());
Matched: 10259, Modified: 10259, Upserted ID: null
Return Value
The updateOne() and updateMany() methods each return an UpdateResult object. The UpdateResult type contains the following instance methods:
Method | Description |
|---|---|
| The number of documents that matched the query filter, regardless of how many were updated. |
| The number of documents modified by the update operation. If an updated document is identical to the original, it is not included in this count. |
| The ID of the document that was upserted in the database, if the driver
performed an upsert. Otherwise |
| Returns true if the update was acknowledged. |
Additional Information
For additional information about update operators, see Update Operators in the MongoDB Server manual.
For runnable code examples of inserting documents with the Java Reactive Streams driver, see the CRUD Operations guide.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: