您只能使用$pull运算符来删除和更新MongoDB中的现有记录。首先让我们创建一个包含文档的集合-
> db.removeDemo.insertOne( ... { ... "UserName" : "Larry", ... "UserDetails" : [ ... { ... "_id" : 101, ... "UserEmailId" : "976Larry@gmail.com", ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc7f9f88f9e6ff3eb0ce446") } > db.removeDemo.insertOne( ... { ... "UserName" : "Mike", ... "UserDetails" : [ ... { ... "_id" : 102, ... "UserEmailId" : "Mike121@gmail.com", ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc7f9f98f9e6ff3eb0ce447") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.removeDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"), "UserName" : "Larry", "UserDetails" : [ { "_id" : 101, "UserEmailId" : "976Larry@gmail.com" } ] } { "_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"), "UserName" : "Mike", "UserDetails" : [ { "_id" : 102, "UserEmailId" : "Mike121@gmail.com" } ] }
现在让我们实现$pull查询以删除和更新现有记录-
> db.removeDemo.update( ... {"_id": ObjectId("5cc7f9f98f9e6ff3eb0ce447")}, ... { "$pull": { "UserDetails": {"_id": 102}}} ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们显示集合中的文档,以检查对象是否已移除-
> db.removeDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"), "UserName" : "Larry", "UserDetails" : [ { "_id" : 101, "UserEmailId" : "976Larry@gmail.com" } ] } { "_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"), "UserName" : "Mike", "UserDetails" : [ ] }