Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Update Multiple Documents

Note

If you specify a callback method, updateMany() returns nothing. If you do 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 see the API documentation for information on the result object.

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.

Note

This example connects to an instance of MongoDB and uses a sample data database. To learn more about connecting to your MongoDB instance and loading this database, see the Usage Examples 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 useNewUrlParser: true,
9 useUnifiedTopology: true,
10});
11
12async function run() {
13 try {
14 await client.connect();
15
16 const database = client.db("sample_mflix");
17 const movies = database.collection("movies");
18
19 // create a filter to update all movies with a 'G' rating
20 const filter = { rated: "G" };
21
22 // increment every document matching the filter with 2 more comments
23 const updateDoc = {
24 $inc: {
25 num_mflix_comments: 2,
26 },
27 };
28 const result = await movies.updateMany(filter, updateDoc);
29 console.log(result);
30 } finally {
31 await client.close();
32 }
33}
34run().catch(console.dir);
←  Update a DocumentReplace a Document →