0

如何拉出有键的内部数组address1

"_id": 2,
"info": {
    "address1": {
        "city": {
            "0": "Indore"
        },
        "state": {
            "0": "MP"
        }
    },
    "address2": {
        "city": {
            "0": "Mhow"
        },
        "state": {
            "0": "MP"
        }
    }
}

删除数据后应该是:

"_id": 2,
"info": {
    "address1": {
        "city": {
            "0": "Indore"
        },
        "state": {
            "0": "MP"
        }
    }
}

我用过这个db.info.update({"_id":2},{'$pull':{"info":{"address1":{'$exists':true}}}}) 但它给出了错误Cannot apply $pull/$pullAll modifier to non-array

4

2 回答 2

1

在我看来,您真正想要的是一组地址,对吧?所以你的用户可以拥有无​​限的地址?如果是这样,您应该有一个数组,如下所示:

"_id": 2,
"info": {
    "address": [{
        "city": {
            "0": "Indore"
        },
        "state": {
            "0": "MP"
        }
    },
     {
        "city": {
            "0": "Mhow"
        },
        "state": {
            "0": "MP"
        }
    }]
}

现在将地址作为数组使用,您可以使用 $push 和 $pull

于 2012-04-10T06:36:47.013 回答
0

从 mongo 控制台:

> db.tester.find()
{ "_id" : 2, "info" : { "address1" : { "city" : { "0" : "Indore" }, "state" : { "0" : "MP" } }, "address2" : { "city" : { "0" : "Mhow" }, "state" : { "0" : "MP" } } } }
> db.tester.findAndModify({query: {"_id":2}, update : {$unset: {"info.address2":1}}, new:true})
{
    "_id" : 2,
    "info" : {
        "address1" : {
            "city" : {
                "0" : "Indore"
            },
            "state" : {
                "0" : "MP"
            }
        }
    }
}
> db.tester.find()
{ "_id" : 2, "info" : { "address1" : { "city" : { "0" : "Indore" }, "state" : { "0" : "MP" } } } }

这能满足您的需要吗?

于 2012-04-10T06:07:17.793 回答