只删除 MongoDB 中的一个文档?
要仅删除单个文档,请remove()在MongoDB中使用。让我们首先创建一个包含文档的集合-
> db.removeOnlyOneDocumentDemo.insertOne({"FirstName":"John","LastName":"Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6ca2f9cb58ca2b005e674") } > db.removeOnlyOneDocumentDemo.insertOne({"FirstName":"Carol","LastName":"Taylor"}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6ca399cb58ca2b005e675") } > db.removeOnlyOneDocumentDemo.insertOne({"FirstName":"David","LastName":"Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5cc6ca429cb58ca2b005e676") }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.removeOnlyOneDocumentDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc6ca2f9cb58ca2b005e674"), "FirstName" : "John", "LastName" : "Smith" } { "_id" : ObjectId("5cc6ca399cb58ca2b005e675"), "FirstName" : "Carol", "LastName" : "Taylor" } { "_id" : ObjectId("5cc6ca429cb58ca2b005e676"), "FirstName" : "David", "LastName" : "Miller" }
以下是仅删除MongoDB中的一个文档的查询。在这里,我们将删除带有“名字”大卫的文档-
> var documentValue = db.removeOnlyOneDocumentDemo.findOne({'FirstName':'David'}); > db.removeOnlyOneDocumentDemo.remove({_id:documentValue._id}); WriteResult({ "nRemoved" : 1 })
让我们检查一个文档是否已从集合中删除-
> db.removeOnlyOneDocumentDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc6ca2f9cb58ca2b005e674"), "FirstName" : "John", "LastName" : "Smith" } { "_id" : ObjectId("5cc6ca399cb58ca2b005e675"), "FirstName" : "Carol", "LastName" : "Taylor" }