Docs HomeNode.js

Update Multiple Documents更新多个文档

You can update multiple documents using the collection.updateMany() method. 您可以使用collection.updateMany()方法更新多个文档。The updateMany() method accepts a filter document and an update document. updateMany()方法接受一个筛选文档和一个更新文档。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.您可以在updateMany()方法的第三个参数中传递的options对象中指定其他选项。有关更多详细信息,请参阅updateMany()API文档

Example示例

Note

You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. 您可以使用此示例连接到MongoDB的实例,并与包含示例数据的数据库进行交互。To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.要了解有关连接到MongoDB实例和加载示例数据集的更多信息,请参阅用法实例指南

import { MongoClient } from "mongodb";

// Replace the uri string with your MongoDB deployment's connection string.将uri字符串替换为MongoDB部署的连接字符串。
const 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 to update all movies with a 'G' rating创建一个筛选器以更新所有评级为“G”的电影
const filter = { rated: "G" };

// increment every document matching the filter with 2 more comments将每个与筛选器匹配的文档增加2条注释
const updateDoc = {
$set: {
random_review: `After viewing I am ${
100 * Math.random()
}% more satisfied with life.`,
},
};
const result = await movies.updateMany(filter, updateDoc);
console.log(`Updated ${result.modifiedCount} documents`);
} finally {
await client.close();
}
}
run().catch(console.dir);

If you run the preceding example, you should see the following output:如果运行前面的示例,您应该会看到以下输出:

Updated 477 documents