Update Multiple Documents
You can update multiple documents using the
collection.updateMany() method.
The updateMany()
method accepts a filter document and an update document. If the query matches documents in the
collection, the method applies the updates from the update document to fields
and values of the matching documents. The update document requires an update operator to modify a field in a document.
You can specify additional options in the options
object passed in
the third parameter of the updateMany()
method. For more detailed
information, see
the updateMany() API documentation.
Example
Note
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("sample_mflix"); 11 const movies = database.collection("movies"); 12 13 // create a filter to update all movies with a 'G' rating 14 const filter = { rated: "G" }; 15 16 // increment every document matching the filter with 2 more comments 17 const updateDoc = { 18 $set: { 19 random_review: `After viewing I am ${ 20 100 * Math.random() 21 }% more satisfied with life.`, 22 }, 23 }; 24 const result = await movies.updateMany(filter, updateDoc); 25 console.log(`Updated ${result.modifiedCount} documents`); 26 } finally { 27 await client.close(); 28 } 29 } 30 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 enum Rating { 9 G = "G", 10 PG = "PG", 11 PG_13 = "PG-13", 12 R = "R", 13 NR = "NOT RATED", 14 } 15 16 interface Movie { 17 rated: Rating; 18 random_review?: string; 19 } 20 21 async function run() { 22 try { 23 const database = client.db("sample_mflix"); 24 const movies = database.collection<Movie>("movies"); 25 const result = await movies.updateMany( 26 { rated: Rating.G }, 27 { 28 $set: { 29 random_review: `After viewing I am ${ 30 100 * Math.random() 31 }% more satisfied with life.`, 32 }, 33 } 34 ); 35 console.log(`Updated ${result.modifiedCount} documents`); 36 } finally { 37 await client.close(); 38 } 39 } 40 run().catch(console.dir);
If you run the preceding example, you should see the following output:
Updated 477 documents