从 MongoDB 中的子数组的子项中提取元素来?
要提取元素,请使用 $$pull 以及 $$(位置) 运算符。让我们创建一个包含文档的集合 −
> db.demo679.insertOne( ... { ... id:1, ... "details": [ ... { ... CountryName:"US", ... "information": [ ... ... { "Name": "Chris", "FirstName": "Name=Chris" }, ... ... {"Name": "Bob", "FirstName": "Name=Bob" } ... ] ... }, ... { ... CountryName:"UK", ... "information": [ ... ... { "Name": "Robert", "FirstName": "Name=Robert" }, ... ... {"Name": "Sam", "FirstName": "Name=Sam" } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea442cf04263e90dac943fd") }
使用 find() 方法在集合中显示所有文档 −
> db.demo679.find();
这将产生以下输出 −
{ "_id" : ObjectId("5ea442cf04263e90dac943fd"), "id" : 1, "details" : [ { "CountryName" : "US", "information" : [ { "Name" : "Chris", "FirstName" : "Name=Chris" }, { "Name" : "Bob", "FirstName" : "Name=Bob" } ] }, { "CountryName" : "UK", "information" : [ { "Name" : "Robert", "FirstName" : "Name=Robert" }, { "Name" : "Sam", "FirstName" : "Name=Sam" } ] } ] }
以下是 MongoDB 中在子数组的子代中提取元素的查询 −
> db.demo679.update( ... { "details.CountryName":"US" }, ... { $pull: { 'details.$.information': { "Name" : "Bob", "FirstName" : "Name=Bob" } } } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
使用 find() 方法在集合中显示所有文档 −
> db.demo679.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5ea442cf04263e90dac943fd"), "id" : 1, "details" : [ { "CountryName" : "US", "information" : [ { "Name" : "Chris", "FirstName" : "Name=Chris" } ] }, { "CountryName" : "UK", "information" : [ { "Name" : "Robert", "FirstName" : "Name=Robert" }, { "Name" : "Sam", "FirstName" : "Name=Sam" } ] } ] }
广告