Delete a Document删除一个文档
You can delete a single document in a collection with 您可以使用collection.deleteOne()
. collection.deleteOne()
删除集合中的单个文档。The deleteOne()
method uses a query document that you provide to match the subset of the documents in the collection that match the query. deleteOne()
方法使用您提供的查询文档来匹配集合中与查询匹配的文档子集。If you do not provide a query document (or if you provide an empty document), MongoDB matches all documents in the collection and deletes the first match.如果您没有提供查询文档(或者提供了一个空文档),MongoDB将匹配集合中的所有文档,并删除第一个匹配的文档。
You can specify additional query options using the 您可以使用作为options
object passed as the second parameter of the deleteOne
method. deleteOne
方法的第二个参数传递的options
对象来指定其他查询选项。For more information on this method, see the deleteOne() API documentation.有关此方法的更多信息,请参阅deleteOne()
API文档。
If your application requires the deleted document after deletion, consider using the collection.findOneAndDelete()如果您的应用程序在删除后需要已删除的文档,请考虑使用 method, which has a similar interface to
deleteOne()
but also returns the deleted document.collection.findOneAndDelete()
。方法,该方法具有与
deleteOne()
类似的接口,但也返回已删除的文档。
Example实例
The following snippet deletes a single document from the 以下片段从movies
collection. movies
集合中删除一个文档。It uses a query document that configures the query to match movies with a 它使用一个查询文档,该文档将查询配置为匹配title
value of "Annie Hall".title
值为“Annie Hall”的电影。
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 a movie that has title "Annie Hall"查询标题为“安妮·霍尔”的电影
const query = { title: "Annie Hall" };
const result = await movies.deleteOne(query);
if (result.deletedCount === 1) {
console.log("Successfully deleted one document.");
} else {
console.log("No documents matched the query. Deleted 0 documents.");
}
} finally {
await client.close();
}
}
run().catch(console.dir);
Identical Code Snippets相同的代码段
The JavaScript and TypeScript code snippets above are identical. 上面的JavaScript和TypeScript代码片段是相同的。There are no TypeScript specific features of the driver relevant to this use case.驱动程序没有与此用例相关的TypeScript特定功能。
If you run the preceding example, you should see the following output:如果运行前面的示例,您应该会看到以下输出:
Successfully deleted one document.
On subsequent runs of the preceding example, as you already deleted the document that matched your query, you should see the following output:在前面示例的后续运行中,由于您已经删除了与查询匹配的文档,因此您应该看到以下输出:
No documents matched the query. Deleted 0 documents.