如何從 MongoDB 文件中的雙重巢狀陣列中刪除一個元素?
若要從 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() 方法的所有文件。該查詢如下所示 −
> 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” 已從雙重巢狀陣列中刪除。
廣告