MongoDB 查询以从文档中删除子文档?
若要从文档中删除子文档,沿用 $pull 并与 update() 结合使用。我们首先使用文档创建集合 -
> db.demo538.insertOne( ... { ... id:101, ... "details": ... { ... anotherDetails: ... [ ... { ... "Name":"Chris", ... Age:21 ... }, ... { ... "Name":"David", ... Age:23 ... }, ... { ... "Name":"Bob", ... Age:20 ... } ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8c8f0aef4dcbee04fbbc08") }
在集合中,借助 find() 方法显示所有文档 -
> db.demo538.find();
这会产生以下输出 -
{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 20 } ] } }
以下是从文档中删除子文档的查询 -
> db.demo538.update({ id:101}, ... {$pull : { "details.anotherDetails" : {"Age":23} } } ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在集合中,借助 find() 方法显示所有文档 -
> db.demo538.find();
这会产生以下输出 -
{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 20 } ] } }
广告