On this page
Overview
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.
Update Documents
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.
Example
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 5 const 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.
updateOne() Example: Full File
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 the free tier of MongoDB Atlas by
following the Get Started with Atlas Guide.
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:
1 // Update a document 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Create a filter for movies with the title "Random Harvest" 16 const filter = { title: "Random Harvest" }; 17 18 /* Set the upsert option to insert a document if no documents match 19 the filter */ 20 const options = { upsert: true }; 21 22 // Specify the update to set a value for the plot field 23 const updateDoc = { 24 $set: { 25 plot: `A harvest of random numbers, such as: ${Math.random()}` 26 }, 27 }; 28 29 // Update the first document that matches the filter 30 const result = await movies.updateOne(filter, updateDoc, options); 31 32 // Print the number of matching and modified documents 33 console.log( 34 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`, 35 ); 36 } finally { 37 // Close the connection after the operation completes 38 await client.close(); 39 } 40 } 41 // Run the program and print any thrown errors 42 run().catch(console.dir);
1 // Update a document 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 // Define the Movie interface 11 interface Movie { 12 plot: string; 13 title: string; 14 } 15 16 async function run() { 17 try { 18 const database = client.db("sample_mflix"); 19 const movies = database.collection<Movie>("movies"); 20 21 /* Update a document that has the title "Random Harvest" to have a 22 plot field with the specified value */ 23 const result = await movies.updateOne( 24 { title: "Random Harvest" }, 25 { 26 $set: { 27 plot: `A harvest of random numbers, such as: ${Math.random()}`, 28 }, 29 }, 30 /* Set the upsert option to insert a document if no documents 31 match the filter */ 32 { upsert: true } 33 ); 34 35 // Print the number of matching and modified documents 36 console.log( 37 `${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)` 38 ); 39 } finally { 40 // Close the connection after the operation completes 41 await client.close(); 42 } 43 } 44 // Run the program and print any thrown errors 45 run().catch(console.dir);
Running the preceding example results in the following output:
1 document(s) matched the filter, updated 1 document(s)
updateMany() Example: Full File
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 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 many operation:
1 /* Update multiple documents */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 // Get the "movies" collection in the "sample_mflix" database 13 const database = client.db("sample_mflix"); 14 const movies = database.collection("movies"); 15 16 // Create a filter to update all movies with a 'G' rating 17 const filter = { rated: "G" }; 18 19 // Create an update document specifying the change to make 20 const updateDoc = { 21 $set: { 22 random_review: `After viewing I am ${ 23 100 * Math.random() 24 }% more satisfied with life.`, 25 }, 26 }; 27 // Update the documents that match the specified filter 28 const result = await movies.updateMany(filter, updateDoc); 29 console.log(`Updated ${result.modifiedCount} documents`); 30 } finally { 31 // Close the database connection on completion or error 32 await client.close(); 33 } 34 } 35 run().catch(console.dir);
1 /* Update multiple documents */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string. 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 enum Rating { 11 G = "G", 12 PG = "PG", 13 PG_13 = "PG-13", 14 R = "R", 15 NR = "NOT RATED", 16 } 17 18 // Create a Movie interface 19 interface Movie { 20 rated: Rating; 21 random_review?: string; 22 } 23 24 async function run() { 25 try { 26 // Get the "movies" collection in the "sample_mflix" database 27 const database = client.db("sample_mflix"); 28 const movies = database.collection<Movie>("movies"); 29 30 // Update all documents that match the specified filter 31 const result = await movies.updateMany( 32 { rated: Rating.G }, 33 { 34 $set: { 35 random_review: `After viewing I am ${ 36 100 * Math.random() 37 }% more satisfied with life.`, 38 }, 39 } 40 ); 41 console.log(`Updated ${result.modifiedCount} documents`); 42 } finally { 43 // Close the database connection on completion or error 44 await client.close(); 45 } 46 } 47 run().catch(console.dir);
Running the preceding example, you see an output like the following:
Updated 477 documents
API Documentation
To learn more about any of the types or methods discussed in this guide, see the following API documentation: