如何在mongodb文件中更新数组元素?

时间:2018-01-17 12:48:33

标签: mongodb mongo-shell

此查询已成功更新:

db.product.updateMany({"Rno":{$in:["111","222","333"]}},{$set:{"subjwmarks.maths":99}});

更新前:

{
    "_id" : ObjectId("5a572886964d881dab9f1f55"),
    "Rno" : "111",
    "stuname" : "sravan",
    "subjwmarks" : [ 
        {
            "maths" : 88.0,
            "english" : 99.0,
            "Clang" : 97.0
        }
    ],
    "total" : 284.0,
    "grade" : "A",
    "organization" : "Tata"
};

更新查询后返回此值:

{
    "_id" : ObjectId("5a572886964d881dab9f1f55"),
    "Rno" : "111",
    "stuname" : "sravan",
    "subjwmarks" : [ 
        {
            "maths" : 99,
        }
    ],
    "total" : 284.0,
    "grade" : "A",
    "organization" : "Tata"
};

值应为:

{
    "_id" : ObjectId("5a572886964d881dab9f1f55"),
    "Rno" : "111",
    "stuname" : "sravan",
    "subjwmarks" : [ 
        {
            "maths" : 99,
            "english" : 99.0,
            "Clang" : 97.0
        }
    ],
    "total" : 284.0,
    "grade" : "A",
    "organization" : "Tata"
}

但该数组的其他元素已被删除。

有人可以建议如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

db.product.updateMany({"Rno":{$in:["111","222","333"]}, subjwmarks:{ $exists: true}},{$set:{"subjwmarks.$.maths":100}});

https://docs.mongodb.com/manual/reference/operator/update/positional/

Note: subjwmarks must be in query part