Docs 菜单
Docs 主页
/ / /
Node.js 驱动程序
/ /

更新多个文档

您可以使用 collection.updateMany() 方法更新多个文档。updateMany() 方法接受一个过滤器文档和一个更新文档。如果查询与集合中的文档匹配,则该方法会将更新文档中的更新应用于匹配文档的字段和值。更新文档需要更新操作符来修改文档中的字段。

您可以在options 方法的第三个参数中传递的updateMany() 对象中指定更多选项。有关更多详细信息,请参阅 updateMany() API 文档。

注意

您可以使用此示例连接到 MongoDB 实例,并与包含样本数据的数据库进行交互。要了解有关连接到 MongoDB 实例和加载样本数据集的更多信息,请参阅使用示例指南。

1/* Update multiple documents */
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10async 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}
35run().catch(console.dir);
1/* Update multiple documents */
2
3import { MongoClient } from "mongodb";
4
5// Replace the uri string with your MongoDB deployment's connection string.
6const uri = "<connection string uri>";
7
8const client = new MongoClient(uri);
9
10enum 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
19interface Movie {
20 rated: Rating;
21 random_review?: string;
22}
23
24async 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}
47run().catch(console.dir);

运行前面的示例,您将看到以下输出:

Updated 477 documents

后退

更新文档

来年

替换文档