要从MongoDB文档中的双嵌套数组中删除元素,可以使用$pull运算符。
为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.removeElementFromDoublyNestedArrayDemo.insertOne( ... { ... "_id" : "1", ... "UserName" : "Larry", ... "UserDetails" : [ ... { ... "UserCountryName" : "US", ... "UserLocation" : [ ... { ... "UserCityName" : "New York" ... }, ... { ... "UserZipCode" : "10001" ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : "1" } > db.removeElementFromDoublyNestedArrayDemo.insertOne( ... { ... "_id" : "2", ... "UserName" : "Mike", ... "UserDetails" : [ ... { ... "UserCountryName" : "UK", ... "UserLocation" : [ ... { ... "UserCityName" : "Bangor" ... }, ... { ... "UserZipCode" : "20010" ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : "2" }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.removeElementFromDoublyNestedArrayDemo.find().pretty();
以下是输出-
{ "_id" : "1", "UserName" : "Larry", "UserDetails" : [ { "UserCountryName" : "US", "UserLocation" : [ { "UserCityName" : "New York" }, { "UserZipCode" : "10001" } ] } ] } { "_id" : "2", "UserName" : "Mike", "UserDetails" : [ { "UserCountryName" : "UK", "UserLocation" : [ { "UserCityName" : "Bangor" }, { "UserZipCode" : "20010" } ] } ] }
这是从MongoDB文档中的双嵌套数组中删除元素的查询-
> db.removeElementFromDoublyNestedArrayDemo.update( ... { _id : "2" }, ... {$pull : {"UserDetails.0.UserLocation" : {"UserZipCode":"20010"}}} ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们借助来检查集合中的文档find()
。查询如下-
> db.removeElementFromDoublyNestedArrayDemo.find().pretty();
以下是输出-
{ "_id" : "1", "UserName" : "Larry", "UserDetails" : [ { "UserCountryName" : "US", "UserLocation" : [ { "UserCityName" : "New York" }, { "UserZipCode" : "10001" } ] } ] } { "_id" : "2", "UserName" : "Mike", "UserDetails" : [ { "UserCountryName" : "UK", "UserLocation" : [ { "UserCityName" : "Bangor" } ] } ] }
现在,字段“ UserZipCode”:“ 20010”已从双重嵌套数组中删除。