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

How to update field in document sub-array in mongo

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

{
        "_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
                }                
        ],
}

如何将 lid:"Qitula"dogfood 更新为 catfood?我试过

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

没有成功。

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

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

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

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