Docs Home → Develop Applications → MongoDB Drivers → Java Sync
Update Multiple Documents
You can update multiple documents using the updateMany()
method on
a MongoCollection
object. The method accepts a filter that matches the
document you want to update and an update statement that instructs the
driver how to change the matching document. The updateMany()
method updates
all the documents in the collection that match the filter.
To perform an update with the updateMany()
method, you must pass
a query filter and an update document. The query filter specifies which
documents in the collection to match and the update document provides
instructions on what changes to make to them.
You can optionally pass an instance of UpdateOptions
to the updateMany()
method in
order to modify the behavior of the call. For example, if you set the
upsert
field of the UpdateOptions
object to true
and no documents
match the specified query filter, the operation inserts a new document
composed of the fields from both the query and update document.
Upon successful execution, the updateMany()
method returns an instance
of UpdateResult
. You can retrieve information such as the number of
documents modified by calling the getModifiedCount()
method. If you
specified upsert(true)
in an UpdateOptions
object and the
operation results in an insert, you can retrieve the _id
field of the
new document by calling the getUpsertedId()
method on the
UpdateResult
instance.
If your update operation fails, the driver raises an exception and does not update
any of the documents matching the filter. For example, if you try to set
a value for the immutable field _id
in your update document, the
updateMany()
method does not update any documents and throws a
MongoWriteException
with the message:
Performing an update on the path '_id' would modify the immutable field '_id'
If your update document contains a change that violates unique index
rules, the method throws a MongoWriteException
with an error
message that should look something like this:
E11000 duplicate key error collection: ...
For more information on the types of exceptions raised under specific
conditions, see the API documentation for updateMany()
, linked at the
bottom of this page.
Example
In this example, we update documents that match our query in the movies
collection of the sample_mflix
database. We perform the following
updates to the matching documents:
Add
Frequently Discussed
to the array ofgenres
only if it does not already existSet the value of
lastUpdated
to the current time.
We use the Updates
builder, a factory class that contains static
helper methods to construct the update document. While you can pass an update
document instead of using the builder, the builder provides type checking and
simplified syntax. Read our
guide on Updates in the Builders
section for more information.
Note
This example connects to an instance of MongoDB using a connection URI. To learn more about connecting to your MongoDB instance, see the connection guide.
package usage.examples; import static com.mongodb.client.model.Filters.gt; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Updates; import com.mongodb.client.result.UpdateResult; public class UpdateMany { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); Bson query = gt("num_mflix_comments", 50); Bson updates = Updates.combine( Updates.addToSet("genres", "Frequently Discussed"), Updates.currentTimestamp("lastUpdated")); try { UpdateResult result = collection.updateMany(query, updates); System.out.println("Modified document count: " + result.getModifiedCount()); } catch (MongoException me) { System.err.println("Unable to update due to an error: " + me); } } } }
After you run the example, you should see output that looks something like this:
Modified document count: 53
If you query the updated document or documents, they should look something like this:
[ Document { { _id=..., plot=..., genres=[..., Frequently Discussed, ...], ... lastUpdated=Timestamp{...} } }, ... ]
Tip
Legacy API
If you are using the legacy API, see our FAQ page to learn what changes you need to make to this code example.
For additional information on the classes and methods mentioned on this page, see the following API Documentation: