Navigation

Update Multiple Documents

Info With Circle IconCreated with Sketch.Note

If you specify a callback method, updateMany() returns nothing. If you not specify one, this method returns a Promise that resolves to the result object when it completes. See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.

You can update multiple documents using the updateMany() method. updateMany() accepts a filter object and update document, and replaces documents in a collection that match the filter with the update document. 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.

Info With Circle IconCreated with Sketch.Note

This example connects to an instance of MongoDB using a connection string. To learn more about connecting to your MongoDB instance, see the connection guide.

1const { MongoClient } = require("mongodb");
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri =
5 "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
6
7const client = new MongoClient(uri);
8
9async function run() {
10 try {
11 await client.connect();
12
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 // increment every document matching the filter with 2 more comments
20 const updateDoc = {
21 $inc: {
22 num_mflix_comments: 2,
23 },
24 };
25 const result = await movies.updateMany(filter, updateDoc);
26 console.log(result);
27 } finally {
28 await client.close();
29 }
30}
31run().catch(console.dir);
Give Feedback