Delete Multiple Documents删除多个文档
You can delete multiple documents in a collection at once using the collection.deleteMany()您可以使用 method.
collection.deleteMany()
方法一次删除集合中的多个文档。
Pass a query document to the 将查询文档传递给deleteMany()
method to specify a subset of documents in the collection to delete. deleteMany()
方法,以指定集合中要删除的文档子集。If you do not provide a query document (or if you provide an empty document), MongoDB matches all documents in the collection and deletes them. While you can use 如果您没有提供查询文档(或者提供了一个空文档),MongoDB会匹配集合中的所有文档并将其删除。虽然可以使用deleteMany()
to delete all documents in a collection, consider using drop() instead for better performance and clearer code.
deleteMany()
删除集合中的所有文档,但为了获得更好的性能和更清晰的代码,可以考虑使用drop()
。
You can specify additional options in the 您可以在options
object passed in the second parameter of the deleteMany()
method. deleteMany()
方法的第二个参数中传递的options
对象中指定其他选项。For more detailed information, see the deleteMany() API documentation.有关更多详细信息,请参阅deleteMany()
API文档。
Example实例
The following snippet deletes multiple documents from the 以下片段从movies
collection. movies
集合中删除了多个文档。It uses a query document that configures the query to match and delete movies with the title "Santa Claus".它使用一个查询文档来配置查询,以匹配和删除标题为“圣诞老人”的电影。
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");
//Query for all movies with a title containing the string "Santa"查询标题包含字符串“Santa”的所有电影
const query = { title: { $regex: "Santa" } };
const result = await movies.deleteMany(query);
console.log("Deleted " + result.deletedCount + " documents");
} finally {
await client.close();
}
}
run().catch(console.dir);
The first time you run the preceding example, you should see the following output:第一次运行前面的示例时,应该会看到以下输出:
Deleted 19 documents
On subsequent runs of the example, as you already deleted all relevant documents, you should see the following output:在该示例的后续运行中,由于您已经删除了所有相关文档,您应该会看到以下输出:
Deleted 0 documents