ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

Update Documents

In this guide, you can learn how to update documents in a MongoDB collection. Update operations specify the fields and values to change in one or more documents. They apply changes specified in an update document to one or more documents that match your query filter.

To learn how to updated embedded arrays or to update or insert in a single operation, see the following pages:

Update operations can modify fields and values:

  • The updateOne() method changes the first document your query filter matches and the

  • updateMany() method changes all the documents your query filter matches.

You can call the updateOne() and updateMany() methods on a MongoCollection instance as follows:

collection.updateOne(<query>, <updateDocument>);
collection.updateMany(<query>, <updateDocument>);

The updateOne() and updateMany() methods both have the following parameters:

  • query specifies a query filter with the criteria to match documents to update in your collection.

  • update specifies the fields and values to modify in the matching document or documents. The examples in this section use the Updates Builders to create the update document.

  • (Optional) updateOptions specifies options that you can set to customize how the driver performs the update operation. To learn more about this type, see the API documentation for UpdateOptions.

You can create the updateDocument using an Updates builder as follows:

Bson update = Updates.operator(<field>, <value>);

To view a complete list of Updates builders and their usage, see Updates in the API documentation.

In the following examples, a paint store sells five different colors of paint. The paint_inventory collection represents their current inventory:

{ "_id": 1, "color": "red", "qty": 5 }
{ "_id": 2, "color": "purple", "qty": 8 }
{ "_id": 3, "color": "yellow", "qty": 0 }
{ "_id": 4, "color": "green", "qty": 6 }
{ "_id": 5, "color": "pink", "qty": 0 }

The following example demonstrates how to change the value of the color field in the first matching document in which the value of qty is 0:

Bson filter = Filters.eq("qty", 0);
Bson update = Updates.set("color", "dandelion");
// Updates first matching document
UpdateResult result = collection.updateOne(filter, update);

If multiple documents match the query filter specified in the updateOne() method, it updates the first result. You can specify a sort in an UpdateOptions instance to apply an order to matched documents before the server performs the update operation, as shown in the following code:

UpdateOptions options = UpdateOptions.sort(ascending("color"));
UpdateResult result = collection.updateOne(filter, document, options);

The paint store receives a fresh shipment and needs to update their inventory. The shipment contains 20 cans of each paint color.

To update the inventory, call the updateMany() method specifying the following:

  • Query filter that matches all the colors

  • Update document that contains instructions to increment the qty field by 20

Bson filter = Filters.empty();
Bson update = Updates.inc("qty", 20);
// Updates all documents and prints the number of matched and modified documents
UpdateResult result = collection.updateMany(filter, update);
System.out.println("Matched document count: " + result.getMatchedCount());
System.out.println("Modified document count: " + result.getModifiedCount());

The output of the preceding code resembles the following:

Matched document count: 5
Modified document count: 5

The following shows the updated documents in the paint_inventory collection:

{ "_id": 1, "color": "red", "qty": 25 }
{ "_id": 2, "color": "purple", "qty": 28 }
{ "_id": 3, "color": "yellow", "qty": 20 }
{ "_id": 4, "color": "green", "qty": 26 }
{ "_id": 5, "color": "pink", "qty": 20 }

If zero documents match the query filter in the update operation, updateMany() makes no changes to documents in the collection. See our upsert guide to learn how to insert a new document instead of updating one if no documents match.

Important

The updateOne() and updateMany() methods cannot make changes to a document that violate unique index constraints on the collection. For more information about constraints on unique indexes, see Unique Indexes in the MongoDB Server manual.

Note

Example Setup

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Create a MongoClient guide. This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. You can load them into your database on the free tier of MongoDB Atlas by following the Get Started with Atlas Guide.

The following code is a complete, standalone file that performs an update one operation and an update many operation:

// Updates the first document that matches a query filter by using the Java driver
package org.example;
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.UpdateOptions;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
import static com.mongodb.client.model.Filters.gt;
public class Update {
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");
// Instructs the driver to insert a new document if none match the query
UpdateOptions options = new UpdateOptions().upsert(true);
Document updateOneQuery = new Document().append("title", "Cool Runnings 2");
// Creates instructions to update the values of three document fields
Bson updateOneUpdates = Updates.combine(
Updates.set("runtime", 99),
Updates.addToSet("genres", "Sports"),
Updates.currentTimestamp("lastUpdated"));
// Updates the first document that has a "title" value of "Cool Runnings 2"
UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options);
// Prints the number of updated documents and the upserted document ID, if an upsert was performed
System.out.println("Number of documents updated - update one: " + result.getModifiedCount());
System.out.println("Upserted document ID: " + result.getUpsertedId());
Bson updateManyQuery = gt("num_mflix_comments", 50);
// Creates instructions to update the values of two document fields
Bson updateManyUpdates = Updates.combine(
Updates.addToSet("genres", "Frequently Discussed"),
Updates.currentTimestamp("lastUpdated"));
// Updates documents that have a "num_mflix_comments" value over 50
UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates);
// Prints the number of updated documents
System.out.println("\nNumber of documents updated - update many: " + result.getModifiedCount());
}
}
}
updateOne() modified document count: 1
Upserted ID: null
updateMany() modified document count: 242

A replace operation substitutes one document from your collection. The substitution occurs between a document your query filter matches and a replacement document.

The replaceOne() method removes all the existing fields and values in the matching document (except the _id field) and substitutes it with the replacement document.

You can call the replaceOne() method on a MongoCollection instance as follows:

collection.replaceOne(<query>, <replacement>);

The replaceOne() method has the following parameters:

  • query specifies a query filter with the criteria to match a document to replace in your collection.

  • replacement specifies fields and values of a new Document object to replace the matched document.

  • (Optional) replaceOptions specifies options that you can set to customize how the driver performs the replace operation. To learn more about this type, see the API documentation for ReplaceOptions.

The paint store realizes they must update their inventory again. What they thought was 20 cans of pink paint is actually 25 cans of orange paint.

To update the inventory, call the replaceOne() method specifying the following:

  • A query filter that matches documents where the color is "pink"

  • A replacement document where the color is "orange" and the qty is "25"

Bson filter = Filters.eq("color", "pink");
Document document = new Document("color", "orange").append("qty", 25);
// Replaces the first document that matches the filter with a new document
UpdateResult result = collection.replaceOne(filter, document);
// Prints the number of matched and modified documents
System.out.println("Matched document count: " + result.getMatchedCount());
System.out.println("Modified document count: " + result.getModifiedCount());

The output of the preceding code resembles the following:

Matched document count: 1
Modified document count: 1

The following shows the updated document:

{ "_id": 5, "color": "orange", "qty": 25 }

If multiple documents match the query filter specified in the replaceOne() method, it replaces the first result. You can specify a sort in a ReplaceOptions instance to apply an order to matched documents before the server performs the replace operation, as shown in the following code:

ReplaceOptions options = ReplaceOptions.sort(ascending("qty"));
UpdateResult result = collection.replaceOne(filter, document, options);

If zero documents match the query filter in the replace operation, replaceOne() makes no changes to documents in the collection. See our upsert guide to learn how to insert a new document instead of replacing one if no documents match.

Important

The replaceOne() method cannot make changes to a document that violate unique index constraints on the collection. For more information about constraints on unique indexes, see Unique Indexes in the MongoDB Server manual.

Note

Example Setup

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Create a MongoClient guide. This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. You can load them into your database on the free tier of MongoDB Atlas by following the Get Started with Atlas Guide.

The following code is a complete, standalone file that performs a replace one operation.

// Replaces the first document that matches a filter by using the Java driver
package org.example;
import static com.mongodb.client.model.Filters.eq;
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.ReplaceOptions;
import com.mongodb.client.result.UpdateResult;
public class ReplaceOne {
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 = eq("title", "Music of the Heart");
// Creates a new document containing "title" and "fullplot" fields
Document replaceDocument = new Document().
append("title", "50 Violins").
append("fullplot", " A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music");
// Instructs the driver to insert a new document if none match the query
ReplaceOptions opts = new ReplaceOptions().upsert(true);
// Replaces the first document that matches the filter with a new document
UpdateResult result = collection.replaceOne(query, replaceDocument, opts);
// Prints the number of modified documents and the upserted document ID, if an upsert was performed
System.out.println("Modified document count: " + result.getModifiedCount());
System.out.println("Upserted id: " + result.getUpsertedId());
// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to replace due to an error: " + me);
}
}
}
Modified document count: 0
Upserted id: BsonObjectId{ ... }

For more information about the methods and classes used on this page, see the following API documentation: