仅使用mongodb和php中的关联键来拉取数据

时间:2012-04-10 05:50:30

标签: php mongodb

如何拉出具有键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

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分: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" } } } }

这是否能满足您的需求?