如何在MongoDB中基于_id删除文档?
要在MongoDB中基于_id删除文档,请实现以下语法
db.yourCollectionName.remove({“_id”:ObjectId(“yourId”});
让我们首先实现以下查询以创建包含文档的集合
>db.removeDocumentOnBasisOfId.insertOne({"UserName":"Larry","UserAge":23,"UserCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c986f9f330fd0aa0d2fe4a3") } >db.removeDocumentOnBasisOfId.insertOne({"UserName":"Sam","UserAge":21,"UserCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c986fb4330fd0aa0d2fe4a4") } >db.removeDocumentOnBasisOfId.insertOne({"UserName":"Chris","UserAge":24,"UserCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c986fc0330fd0aa0d2fe4a5") } >db.removeDocumentOnBasisOfId.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c986fcf330fd0aa0d2fe4a6") } >db.removeDocumentOnBasisOfId.insertOne({"UserName":"David","UserAge":28,"UserCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c986fed330fd0aa0d2fe4a7") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.removeDocumentOnBasisOfId.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c986f9f330fd0aa0d2fe4a3"), "UserName" : "Larry", "UserAge" : 23, "UserCountryName" : "US" } { "_id" : ObjectId("5c986fb4330fd0aa0d2fe4a4"), "UserName" : "Sam", "UserAge" : 21, "UserCountryName" : "UK" } { "_id" : ObjectId("5c986fc0330fd0aa0d2fe4a5"), "UserName" : "Chris", "UserAge" : 24, "UserCountryName" : "US" } { "_id" : ObjectId("5c986fcf330fd0aa0d2fe4a6"), "UserName" : "Robert", "UserAge" : 26, "UserCountryName" : "UK" } { "_id" : ObjectId("5c986fed330fd0aa0d2fe4a7"), "UserName" : "David", "UserAge" : 28, "UserCountryName" : "AUS" }
以下是根据_id删除文档的查询
> db.removeDocumentOnBasisOfId.remove({"_id":ObjectId("5c986fc0330fd0aa0d2fe4a5")}); WriteResult({ "nRemoved" : 1 })
我们已根据上面的_id删除了Chris的记录。现在显示集合中的所有文档以检查文档是否已删除
> db.removeDocumentOnBasisOfId.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c986f9f330fd0aa0d2fe4a3"), "UserName" : "Larry", "UserAge" : 23, "UserCountryName" : "US" } { "_id" : ObjectId("5c986fb4330fd0aa0d2fe4a4"), "UserName" : "Sam", "UserAge" : 21, "UserCountryName" : "UK" } { "_id" : ObjectId("5c986fcf330fd0aa0d2fe4a6"), "UserName" : "Robert", "UserAge" : 26, "UserCountryName" : "UK" } { "_id" : ObjectId("5c986fed330fd0aa0d2fe4a7"), "UserName" : "David", "UserAge" : 28, "UserCountryName" : "AUS" }