Delete a Document删除文件

In this section, we show you how to call the write operations to remove documents from a collection in your MongoDB database.在本节中,我们将向您展示如何调用写入操作以从MongoDB数据库中的集合中删除文档。

If you want to remove existing documents from a collection, you can use deleteOne() to remove one document or deleteMany() for one or more documents. 如果要从集合中删除现有文档,可以使用deleteOne()删除一个文档,或使用deleteMany()删除一个或多个文档。These methods accept a query document that matches the documents you want to delete.这些方法接受与要删除的文档匹配的查询文档。

You can specify the document or documents to be deleted by the deleteOne() or deleteMany() write operations in a JSON object as follows:您可以通过JSON对象中的deleteOne()deleteMany()写入操作指定要删除的一个或多个文档,如下所示:

const doc = {
  pageViews: {
    $gt: 10,
    $lt: 32768
  }
};

To delete the first matching document using the deleteOne() method or to delete all matching documents using the deleteMany() method, pass the document as the method parameter:要使用deleteOne()方法删除第一个匹配文档,或使用deleteMany()方法删除所有匹配文档,请将文档作为方法参数传递:

const deleteResult = await collection.deleteOne(doc);
const deleteManyResult = await collection.deleteMany(doc);

You can print the number of documents deleted by the operation by accessing the deletedCount field of the result for each of the method calls above as follows:通过访问上述每个方法调用的结果的deletedCount字段,可以打印操作删除的文档数,如下所示:

console.dir(deleteResult.deletedCount);
console.dir(deleteManyResult.deletedCount);

Upon successful delete, these statements should print the number of documents deleted by the associated operation.成功删除后,这些语句应打印相关操作删除的文档数。

For fully runnable examples and additional information on the available options, see our usage examples for deleteOne() and deleteMany().有关完全可运行的示例和有关可用选项的其他信息,请参阅deleteOne()deleteMany()的使用示例。