在MongoDB的子数组子数组中提取元素?
为了拉一个元素,使用$沿着拉$(位置)运算符。让我们创建一个包含文档的集合-
> 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" } ] } ] }