删除多个文档
您可以使用以下方式一次删除集合中的多个文档:collection.deleteMany() 方法。传递一个查询文档以指定要删除的集合中的文档子集。如果不提供查询文档(或提供空文档),MongoDB 将匹配集合中的所有文档并将它们删除。虽然可以使用 deleteMany()
删除集合中的所有文档,但请考虑使用 drop() 以获得更好的性能和更清晰的代码。deleteMany()
方法通过传入第二个参数的 options
对象指定更多选项。有关更详细的信息,请参阅 deleteMany() API 文档。
您可以在 deleteMany()
方法的第二个参数传入的 options
对象中指定更多选项。有关更详细的信息,请参阅 deleteMany() API 文档。
示例
以下片段从movies
集合中删除多个文档。它使用一个配置查询以匹配和删除标题为“圣诞老人”的电影的查询文档。
注意
您可以使用此示例连接到MongoDB的一个实例并与之交互,以包含示例数据的数据库。有关连接到您的MongoDB实例和加载示例数据集的更多信息,请参阅使用示例指南.
1 // Delete 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 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 /* Delete all documents that match the specified regular 16 expression in the title field from the "movies" collection */ 17 const query = { title: { $regex: "Santa" } }; 18 const result = await movies.deleteMany(query); 19 20 // Print the number of deleted documents 21 console.log("Deleted " + result.deletedCount + " documents"); 22 } finally { 23 // Close the connection after the operation completes 24 await client.close(); 25 } 26 } 27 // Run the program and print any thrown exceptions 28 run().catch(console.dir);
1 // Delete 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 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 /* Delete all documents that match the specified regular 16 expression in the title field from the "movies" collection */ 17 const result = await movies.deleteMany({ title: { $regex: "Santa" } }); 18 19 // Print the number of deleted documents 20 console.log("Deleted " + result.deletedCount + " documents"); 21 } finally { 22 // Close the connection after the operation completes 23 await client.close(); 24 } 25 } 26 // Run the program and print any thrown exceptions 27 run().catch(console.dir);
首次运行前面的示例时,您将看到以下输出
Deleted 19 documents
如果您多次运行示例,您将看到以下输出,因为在第一次运行中已删除匹配的文档
Deleted 0 documents