【问题标题】:How to update array element in mongodb document?如何更新 mongodb 文档中的数组元素?
【发布时间】:2018-01-17 12:48:33
【问题描述】:

此查询正在成功更新:

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"
}

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

谁能建议如何解决这个问题?

【问题讨论】:

  • 您好,请您提供一个命令前后数据库中的示例;以及你想在命令之后拥有什么,以便我们了解你想要做什么?
  • 更新前:
  • { "_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, } ] ,“总”:284.0,“等级”:“A”,“组织”:“塔塔”}

标签: mongodb mongo-shell


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-19
    • 2022-12-05
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 2019-02-09
    相关资源
    最近更新 更多