Docs 菜单

删除多个文档

您可以使用 collection.deleteMany() 方法同时删除集合中的多个文档。将查询文档传递给 deleteMany() 方法,以指定集合中要删除的部分文档。如果未提供查询文档(或提供空文档),MongoDB 会匹配集合中的所有文档并将其删除。虽然可以使用 deleteMany() 删除集合中的所有文档,但请考虑改用 drop(),以获得更好的性能和更清晰的代码。

您可以使用作为 deleteMany() 方法的第二个参数传递的 options 对象指定更多选项。有关更多详细信息,请参阅 deleteMany() API 文档

以下代码片段从 movies 集合中删除多个文档。它使用一个查询文档,该文档配置查询以匹配和删除标题为“Santa Claus”的电影。

注意

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

1// Delete 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 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
28run().catch(console.dir);
1// Delete 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 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
27run().catch(console.dir);

首次运行上述示例时,会有以下输出:

Deleted 19 documents

如果多次运行该示例,您将看到以下输出,因为您在第一次运行时删除了匹配的文档:

Deleted 0 documents