Docs Home / Node.js Driver

Delete Documents删除文档

Overview概述

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

Delete删除

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. These methods accept a query document that matches the documents you want to delete.如果要从集合中删除现有文档,可以使用deleteOne()删除一个文档,也可以使用deleteMany()删除多个文档。这些方法接受与要删除的文档匹配的查询文档。

Note

If your application uses information about the deleted document after deletion, you can use the collection.findOneAndDelete() method, which has a similar interface to deleteOne() but also returns the deleted document.如果您的应用程序在删除后使用了有关已删除文档的信息,则可以使用collection.findOneAndDelete()方法,该方法具有与deleteOne()类似的接口,但也返回已删除的文档。

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 myColl.deleteOne(doc);
const deleteManyResult = await myColl.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);

If the delete operation is successful, these statements print the number of documents deleted by the associated operation.如果删除操作成功,这些语句将打印相关操作删除的文档数量。

deleteOne() Example: Full FiledeleteOne()示例:完整文件

Note

Example Setup示例设置

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. 此示例还使用Atlas示例数据集中包含的sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。

Note

No TypeScript Specific Features没有TypeScript特定功能

The following code example uses JavaScript. There are no TypeScript specific features of the driver relevant to this use case.以下代码示例使用JavaScript。驱动程序中没有与此用例相关的TypeScript特定功能。

The following code is a complete, standalone file that performs a delete one operation:以下代码是一个完整的独立文件,用于执行删除操作:

// Delete a document删除文档

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");

/* Delete the first document in the "movies" collection that matches the specified query document删除“电影”集合中与指定查询文档匹配的第一个文档 */
const query = { title: "Annie Hall" };
const result = await movies.deleteOne(query);

/* Print a message that indicates whether the operation deleted a document打印一条消息,指示操作是否删除了文档 */
if (result.deletedCount === 1) {
console.log("Successfully deleted one document.");
} else {
console.log("No documents matched the query. Deleted 0 documents.");
}
} finally {
// Close the connection after the operation completes操作完成后关闭连接
await client.close();
}
}
// Run the program and print any thrown exceptions运行程序并打印任何抛出的异常
run().catch(console.dir);

Running the preceding example results in the following output:运行前面的示例会得到以下输出:

Successfully deleted one document.

If you run the example more than once, the code produces the following output because you deleted the matching document in the first run:如果您多次运行该示例,代码将产生以下输出,因为您在第一次运行中删除了匹配的文档:

No documents matched the query. Deleted 0 documents.

deleteMany() Example: Full FiledeleteMany()示例:完整文件

Note

Example Setup示例设置

This example connects to an instance of MongoDB by using a connection URI. To learn more about connecting to your MongoDB instance, see the Connect to MongoDB guide. 此示例通过使用连接URI连接到MongoDB的实例。要了解有关连接到MongoDB实例的更多信息,请参阅连接到MongoDB指南。This example also uses the movies collection in the sample_mflix database included in the Atlas sample datasets. 此示例还使用Atlas示例数据集中包含的sample_mflix数据库中的movies集合。You can load them into your database on the free tier of MongoDB Atlas by following the MongoDB Get Started.您可以按照MongoDB入门指南将它们加载到MongoDB Atlas免费层的数据库中。

The following code is a complete, standalone file that performs a delete many operation:以下代码是一个完整的独立文件,用于执行删除多个操作:

JavaScript
// Delete multiple documents删除多个文档

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");

/* Delete all documents that match the specified regular expression in the title field from the "movies" collection从“电影”集合中删除与标题字段中指定的正则表达式匹配的所有文档 */
const query = { title: { $regex: "Santa" } };
const result = await movies.deleteMany(query);

// Print the number of deleted documents打印已删除文档的数量
console.log("Deleted " + result.deletedCount + " documents");
} finally {
// Close the connection after the operation completes操作完成后关闭连接
await client.close();
}
}
// Run the program and print any thrown exceptions运行程序并打印任何抛出的异常
run().catch(console.dir);
TypeScript
// Delete multiple documents删除多个文档

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");

/* Delete all documents that match the specified regular expression in the title field from the "movies" collection从“电影”集合中删除与标题字段中指定的正则表达式匹配的所有文档 */
const result = await movies.deleteMany({ title: { $regex: "Santa" } });

// Print the number of deleted documents打印已删除文档的数量
console.log("Deleted " + result.deletedCount + " documents");
} finally {
// Close the connection after the operation completes操作完成后关闭连接
await client.close();
}
}
// Run the program and print any thrown exceptions运行程序并打印任何抛出的异常
run().catch(console.dir);

Running the preceding example for the first time results in the following output:第一次运行前面的示例会得到以下输出:

Deleted 19 documents

If you run the example more than once, you see the following output because you deleted the matching documents in the first run:如果您多次运行该示例,则会看到以下输出,因为您在第一次运行中删除了匹配的文档:

Deleted 0 documents

API Documentation文档

To learn more about any of the types or methods discussed in this guide, see the following API documentation:要了解有关本指南中讨论的任何类型或方法的更多信息,请参阅以下API文档: