更新多个文档
您可以使用.updateMany()集合 更新多个文档方法。 updateMany()
方法接受过滤文档和更新文档。 如果查询与集合中的文档匹配,则该方法会将更新文档中的更新应用于匹配文档的字段和值。 更新文档需要更新操作符来修改文档中的字段。
您可以在 updateMany()
方法的第三个参数中传递的 options
对象中指定更多选项。有关更多详细信息,请参阅 updateMany() API 文档。
例子
注意
可以使用此示例连接到 MongoDB 实例,并与包含样本数据的数据库进行交互。如需了解有关连接到 MongoDB 实例和加载样本数据集的更多信息,请参阅使用示例指南。
1 /* Update multiple documents */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async 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 } 35 run().catch(console.dir);
1 /* Update multiple documents */ 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string. 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 enum 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 19 interface Movie { 20 rated: Rating; 21 random_review?: string; 22 } 23 24 async 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 } 47 run().catch(console.dir);
运行前面的示例,您将看到以下输出:
Updated 477 documents