> use test
switched to db test
插入測(cè)試數(shù)據(jù):
> db.country.insert({"name":"China","province":[{"name":"Henan","code":"1001"},{"name":"Hebei","code":"1002"},{"name":"Jiangsu","code":"1003"}]});
WriteResult({ "nInserted" : 1 })
方法一:
想刪除名為"Hebei"的省份信息,分兩步:
(1).查找到對(duì)應(yīng)的數(shù)組元素,并將其替換為"null"
> db.country.update({"name":"China","province.name":"Hebei"},{"$set":{"province.$":"null"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
此時(shí)數(shù)組數(shù)據(jù)如下:
> db.country.find()
{ "_id" : ObjectId("59f97d03a4fe2442400cbd2c"), "name" : "China", "province" : [ { "name" : "Henan", "code" : "1001" }, "null", { "name" : "Jiangsu", "code" : "1003" } ] }
(2).然后再清空數(shù)組中的"null"
> db.country.update({"name":"China"},{"$pull":{"province":"null"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
刪除后的最終數(shù)據(jù)如下:
> db.country.find()
{ "_id" : ObjectId("59f97d03a4fe2442400cbd2c"), "name" : "China", "province" : [ { "name" : "Henan", "code" : "1001" }, { "name" : "Jiangsu", "code" : "1003" } ] }
>
方法二:
根據(jù)某個(gè)鍵直接刪除數(shù)組元素:
> 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" } ] }
>
分享標(biāo)題:MongoDB根據(jù)內(nèi)嵌文檔的某個(gè)鍵刪除數(shù)組元素的兩種方法介紹
本文路徑:
http://m.jiaotiyi.com/article/gpoopd.html