我们专注攀枝花网站设计 攀枝花网站制作 攀枝花网站建设
成都网站建设公司服务热线:400-028-6601

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

MongoDB根据内嵌文档的某个键删除数组元素的两种方法介绍

> 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" } ] }



新闻标题:MongoDB根据内嵌文档的某个键删除数组元素的两种方法介绍
转载源于:http://mswzjz.cn/article/gpoopd.html

其他资讯