对象内部的Mongodb更新数组

时间:2020-02-19 17:14:26

标签: mongodb mongodb-query

我无法编写查询来更新对象内部数组的值:

假设我有一个集合,其中包含具有如下结构的文档条目(示例中有2个条目,但实际上我需要在数据库中更新几千个条目)

/* 1 */
{
    "name" : "Bob",
    "info" : {
        "species" : "human",
        "addresses" : [ 
            "one",
            "two"
        ]
    }
},
/* 2 */
{
    "name" : "John",
    "info" : {
        "species" : "human",
        "addresses" : [ 
            "two",
            "three"
        ]
    },
}

如何更新此集合中的所有文档,以便将info.addresses数组中所有值为one的地址更改为值four

mongo db文档中的

Examples解决了数组不在对象内部但无法使它们与对象内部的数组一起工作的情况

示例-此查询应更新所有文档的所有info.addresses数组,并将条目值从one更改为four

db.getCollection('test').update({"info.addresses": "one"},{ $set: { "info.addresses.$" : "four" } })

2 个答案:

答案 0 :(得分:1)

db.getCollection('test').update({"info.addresses": "one"},{ $set: { "info.addresses.$[]" : "four" } })

注意如何在$ set中指定的数组中添加方括号“ []”。它($ [])是mongodb中的位置运算符。您可以在Mongodb文档中阅读有关它的更多信息。

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

答案 1 :(得分:0)

update替换为updateMany 用于更新所有info.addresses数组。

db.getCollection('text').updateMany( {'info.addresses':'one'}, {$set:{'info.addresses.$':'two'}} )