您可以使用 collection.deleteOne()
删除集合中的单个文档。deleteOne()
方法使用您提供的查询文档来匹配集合中与查询匹配的文档子集。如果未提供查询文档(或提供空文档),MongoDB 将匹配集合中的所有文档并删除首个匹配项。
您可以使用作为deleteOne
方法的第二个参数传递的options
对象来指定更多查询选项。 有关此方法的更多信息,请参阅 deleteOne() API文档。
注意
如果您的应用程序在删除后需要被删除的文档,请考虑使用 collection.findOneAndDelete() 方法,此方法的接口与 deleteOne()
类似的接口 ,但也会返回已删除的文档。
例子
以下代码片段从 movies
集合中删除单个文档。 它使用一个查询文档,该文档配置查询以匹配标题为 title
值“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.