在MongoDB中仅删除一个文档
要仅删除MongoDB中的单个文档,请使用remove()
。让我们创建一个包含文档的集合-
> db.demo165.insertOne({"ClientId":101,"ClientName":"Chris","ClientAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5e36895c9e4f06af551997cc") } > db.demo165.insertOne({"ClientId":102,"ClientName":"Bob","ClientAge":32}); { "acknowledged" : true, "insertedId" : ObjectId("5e3689659e4f06af551997cd") } > db.demo165.insertOne({"ClientId":103,"ClientName":"David","ClientAge":35}); { "acknowledged" : true, "insertedId" : ObjectId("5e36896d9e4f06af551997ce") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo165.find();
这将产生以下输出-
{ "_id" : ObjectId("5e36895c9e4f06af551997cc"), "ClientId" : 101, "ClientName" : "Chris", "ClientAge" : 34 } { "_id" : ObjectId("5e3689659e4f06af551997cd"), "ClientId" : 102, "ClientName" : "Bob", "ClientAge" : 32 } { "_id" : ObjectId("5e36896d9e4f06af551997ce"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }
以下是从MongoDB中删除文档的查询-
> db.demo165.remove({"ClientId":102}); WriteResult({ "nRemoved" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo165.find();
这将产生以下输出-
{ "_id" : ObjectId("5e36895c9e4f06af551997cc"), "ClientId" : 101, "ClientName" : "Chris", "ClientAge" : 34 } { "_id" : ObjectId("5e36896d9e4f06af551997ce"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }