要从文档中删除子文档,请使用$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 } ] } }