删除和更新 MongoDB 中的现有记录?
您只能使用删除和更新 MongoDB 中现有记录的 $pull 运算符。我们首先使用文档创建一个集合 −
> db.removeDemo.insertOne( ... { ... "UserName" : "Larry", ... "UserDetails" : [ ... { ... "_id" : 101, ... "UserEmailId" : "[email protected]", ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc7f9f88f9e6ff3eb0ce446") } > db.removeDemo.insertOne( ... { ... "UserName" : "Mike", ... "UserDetails" : [ ... { ... "_id" : 102, ... "UserEmailId" : "[email protected]", ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cc7f9f98f9e6ff3eb0ce447") }
以下查询使用 find() 方法显示集合中的所有文档 −
> db.removeDemo.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"), "UserName" : "Larry", "UserDetails" : [ { "_id" : 101, "UserEmailId" : "[email protected]" } ] } { "_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"), "UserName" : "Mike", "UserDetails" : [ { "_id" : 102, "UserEmailId" : "[email protected]" } ] }
现在让我们实现 $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" : "[email protected]" } ] } { "_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"), "UserName" : "Mike", "UserDetails" : [ ] }
广告