MongoDB:替换整个数组(如果存在)或者如果它不存在则创建新数组

时间:2013-07-26 07:23:23

标签: mongodb

如果我收集了如下所示的数组,

{
        "_id" : ObjectId("51f21c47564f4a9f411baf8d"),
        "Gender" : [
                {
                        "key" : "m",
                        "desc" : "male"
                }
        ]
}
{
        "_id" : ObjectId("51f21c9a564f4a9f411baf8e"),
        "marital status" : [
                {
                        "key" : "m",
                        "desc" : "married"
                },
                {
                        "key" : "s",
                        "desc" : "single"
                }
        ]
}

如果存在,则替换整个数组的查询是什么?如果不存在则创建新数组?

1 个答案:

答案 0 :(得分:0)

<强>语法:

db.collection.update({<key>: {'$exists': true}}, {<key>: <value>}, 
{upsert: true});

查询以上情景

db.collection.update({"Gender": {'$exists': true}}, {"Gender": 
[{"key": "m", "desc": "male"}, {"key": "f", "desc": "female"}]}, true);