删除文档
您可以使用collection.deleteOne()
在集合中删除单个文档。该方法使用您提供的查询文档来匹配集合中与查询匹配的文档子集。如果您不提供查询文档(或提供空文档),MongoDB 将匹配集合中的所有文档并删除第一个匹配项。
您可以使用 options
对象指定更多查询选项,该对象作为 deleteOne
方法的第二个参数传递。有关此方法的更多信息,请参阅deleteOne() API 文档.
注意
如果您的应用程序在删除后需要删除的文档,请考虑使用collection.findOneAndDelete()方法,该方法与deleteOne()
具有类似接口,但同时也返回被删除的文档。
示例
以下示例从movies
集合中删除单个文档。它使用一个查询文档来配置查询,以匹配标题值为"Annie Hall"的电影。
注意
您可以使用此示例连接到MongoDB的一个实例,并与之交互包含示例数据的数据库。有关连接到您的MongoDB实例和加载示例数据集的更多信息,请参阅使用示例指南.
1 // Delete a document 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 /* Delete the first document in the "movies" collection that matches 16 the specified query document */ 17 const query = { title: "Annie Hall" }; 18 const result = await movies.deleteOne(query); 19 20 /* Print a message that indicates whether the operation deleted a 21 document */ 22 if (result.deletedCount === 1) { 23 console.log("Successfully deleted one document."); 24 } else { 25 console.log("No documents matched the query. Deleted 0 documents."); 26 } 27 } finally { 28 // Close the connection after the operation completes 29 await client.close(); 30 } 31 } 32 // Run the program and print any thrown exceptions 33 run().catch(console.dir);
1 // Delete a document 2 3 import { MongoClient } from "mongodb"; 4 5 // Replace the uri string with your MongoDB deployment's connection string 6 const uri = "<connection string uri>"; 7 8 const client = new MongoClient(uri); 9 10 async function run() { 11 try { 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 /* Delete the first document in the "movies" collection that matches 16 the specified query document */ 17 const query = { title: "Annie Hall" }; 18 const result = await movies.deleteOne(query); 19 20 /* Print a message that indicates whether the operation deleted a 21 document */ 22 if (result.deletedCount === 1) { 23 console.log("Successfully deleted one document."); 24 } else { 25 console.log("No documents matched the query. Deleted 0 documents."); 26 } 27 } finally { 28 // Close the connection after the operation completes 29 await client.close(); 30 } 31 } 32 // Run the program and print any thrown exceptions 33 run().catch(console.dir);
注意
相同的代码片段
上面的JavaScript和TypeScript代码片段是相同的。此用例与驱动程序无关的TypeScript特定功能。
运行前面的示例,您将看到以下输出
Successfully deleted one document.
如果您多次运行此示例,您将看到以下输出,因为在第一次运行中已删除匹配的文档
No documents matched the query. Deleted 0 documents.