MongoDB根據內嵌文件的某個鍵刪除陣列元素的兩種方法介紹

chenfeng發表於2017-11-01
> use test
switched to db test
插入測試資料:
> db.country.insert({"name":"China","province":[{"name":"Henan","code":"1001"},{"name":"Hebei","code":"1002"},{"name":"Jiangsu","code":"1003"}]});
WriteResult({ "nInserted" : 1 })


方法一:
想刪除名為"Hebei"的省份資訊,分兩步:
(1).查詢到對應的陣列元素,並將其替換為"null"


> db.country.update({"name":"China","province.name":"Hebei"},{"$set":{"province.$":"null"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
此時陣列資料如下:
> db.country.find()
{ "_id" : ObjectId("59f97d03a4fe2442400cbd2c"), "name" : "China", "province" : [ { "name" : "Henan", "code" : "1001" }, "null", { "name" : "Jiangsu", "code" : "1003" } ] }


(2).然後再清空陣列中的"null"
> db.country.update({"name":"China"},{"$pull":{"province":"null"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
刪除後的最終資料如下:
> db.country.find()
{ "_id" : ObjectId("59f97d03a4fe2442400cbd2c"), "name" : "China", "province" : [ { "name" : "Henan", "code" : "1001" }, { "name" : "Jiangsu", "code" : "1003" } ] }



方法二:
根據某個鍵直接刪除陣列元素:
> db.country.update({"name":"China"},{"$pull":{"province":{"name":"Hebei"}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.country.find()
{ "_id" : ObjectId("59f97e58a4fe2442400cbd2d"), "name" : "China", "province" : [ { "name" : "Henan", "code" : "1001" }, { "name" : "Jiangsu", "code" : "1003" } ] }


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/15498/viewspace-2146696/,如需轉載,請註明出處,否則將追究法律責任。

相關文章