如何在mongo中更新文档子数组中的字段

时间:2015-02-21 15:39:31

标签: arrays mongodb mongodb-query

在包含这些文件的数据库中

{
        "_id" : ObjectId("5448f241e47010336375bb21"),
        "lid" : "Ridali",
        "items" : [
                {
                        "product" : "dogfood",        ,
                        "done" : false
                }
        ],
}
{
        "_id" : ObjectId("5448fc15e47010336375bb23"),
        "lid" : "Qitula",
        "items" : [
                {
                        "product" : "measure kitchen cab",
                        "done" : false,
                        "tags" : [
                                "11x30"
                        ]
                },
                {
                        "product" : "radiators",
                        "done" : true
                },
                {
                        "product" : "dogfood",
                        "done" : true
                }                
        ],
}

如何为dogfood更新catfoodlid:"Qitula"?我尝试了

的变体
db.lists.update({lid: "Qitula","items: {$elemMatch: {product: "dogfood"}}},{$set: {"items.product": "catfood"}})

没有成功。

2 个答案:

答案 0 :(得分:2)

db.lists.update({lid: "Qitula","items.product": "dogfood" }, { $set : { "items.$.product" : "catfood" }})

检查文档 - http://docs.mongodb.org/manual/reference/operator/update/positional/#up.S

答案 1 :(得分:1)

要更新子文档,您需要使用位置$运算符

db.lists.update({
    lid: "Qitula",
    items: {$elemMatch: {product: "dogfood"}}
    }, 
    {$set: {"items.$.product": "catfood"}
})