For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Modify Documents

You can modify documents in a MongoDB collection by using update and replace operations. Update operations modify the fields and values of a document while keeping other fields and values unchanged. Replace operations substitute all fields and values in an existing document with specified fields and values while keeping the _id field value unchanged.

The Node.js driver provides the following methods to change documents:

  • updateOne()

  • updateMany()

  • replaceOne()

To learn how to replace documents, see the Replace Documents guide.

Tip

Interactive Lab

This page includes a short interactive lab that demonstrates how to modify data by using the updateMany() method. You can complete this lab directly in your browser window without installing MongoDB or a code editor.

To start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button (⛶) in the top-right corner of the lab pane.

To perform an update to one or more documents, create an update document that specifies the update operator (the type of update to perform) and the fields and values that describe the change. Update documents use the following format:

{ <update operator>: { <field> : { ... }, <field> : { } }, <update operator>: { ... }}

The top level of an update document contains one or more of the following update operators:

  • $set: replaces the value of a field with a specified one

  • $inc: increments or decrements field values

  • $rename: renames fields

  • $unset: removes fields

  • $mul: multiplies a field value by a specified number

See the MongoDB Server manual for a complete list of update operators and their usage.

The update operators apply only to the fields associated with them in your update document.

Note

Aggregation Pipelines in Update Operations

If you are using MongoDB Version 4.2 or later, you can use aggregation pipelines made up of a subset of aggregation stages in update operations. For more information on the aggregation stages MongoDB supports in aggregation pipelines used in update operations, see our tutorial on building updates with aggregation pipelines.

Consider a document in the myDB.items collection with fields describing an item for sale, its price, and the quantity available:

{ _id: 465, item: "Hand-thrown ceramic plate", price: 32.50, quantity: 7,}

If you apply the $set update operator with a new value for quantity, you can use the following update document:

const myDB = client.db("myDB");const myColl = myDB.collection("items"); const filter = { _id: 465 }; // update the value of the 'quantity' field to 5const updateDocument = { $set: { quantity: 5, },};const result = await myColl.updateOne(filter, updateDocument);

The updated document resembles the following, with an updated value in the quantity field and all other values unchanged:

{ _id: 465, item: "Hand-thrown ceramic plate", price: 32.50, quantity: 5,}

If an update operation fails to match any documents in a collection, it does not make any changes. Update operations can be configured to perform an upsert which attempts to perform an update, but if no documents are matched, inserts a new document with the specified fields and values.

You cannot modify the _id field of a document nor change a field to a value that violates a unique index constraint. See the MongoDB Server manual for more information on unique indexes.

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 Connect to MongoDB 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 a free cluster in MongoDB Atlas following the MongoDB Get Started.

This example uses the $set update operator which specifies update values for document fields. For more information on update operators, see the MongoDB update operator reference documentation.

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

// Update a document import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection stringconst uri = "<connection string uri>"; const client = new MongoClient(uri); async function run() { try { const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Create a filter for movies with the title "Random Harvest" const filter = { title: "Random Harvest" }; /* Set the upsert option to insert a document if no documents match the filter */ const options = { upsert: true }; // Specify the update to set a value for the plot field const updateDoc = { $set: { plot: `A harvest of random numbers, such as: ${Math.random()}` }, }; // Update the first document that matches the filter const result = await movies.updateOne(filter, updateDoc, options); // Print the number of matching and modified documents console.log( `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`, ); } finally { // Close the connection after the operation completes await client.close(); }}// Run the program and print any thrown errorsrun().catch(console.dir);

Running the preceding example results in the following output:

1 document(s) matched the filter, updated 1 document(s)

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 Connect to MongoDB 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 a free cluster in MongoDB Atlas following the MongoDB Get Started.

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

/* Update multiple documents */ import { MongoClient } from "mongodb"; // Replace the uri string with your MongoDB deployment's connection stringconst uri = "<connection string uri>"; const client = new MongoClient(uri); async function run() { try { // Get the "movies" collection in the "sample_mflix" database const database = client.db("sample_mflix"); const movies = database.collection("movies"); // Create a filter to update all movies with a 'G' rating const filter = { rated: "G" }; // Create an update document specifying the change to make const updateDoc = { $set: { random_review: `After viewing I am ${ 100 * Math.random() }% more satisfied with life.`, }, }; // Update the documents that match the specified filter const result = await movies.updateMany(filter, updateDoc); console.log(`Updated ${result.modifiedCount} documents`); } finally { // Close the database connection on completion or error await client.close(); }}run().catch(console.dir);

Running the preceding example, you see an output like the following:

Updated 477 documents

To learn more about any of the types or methods discussed in this guide, see the following API documentation: