如何一次替换多个 mongodb 文档中嵌套数组中的值

问题描述

在这里,我想将国家的价值替换为其他任何地方,例如“印度”。 我有多个结构相同的文档,想一次性更新。它不应该影响其他键,只是想更新国家/地区。

尝试使用 Set 运算符,但未正确获取

{
    "_id" : "1","teams" : 
    [ 
        {
            "type" : "local","isEnabled" : "true","Country":"India"
            "names" : 
            [ 
                { "name": "kumar","Nationality":"indian","BirthPlace":"Goa","Age":"U25" },{ "name": "kannan","BirthPlace":"Kerala","Age":"U25"}
            ]
        },{
            "type" : "national",{
            "type" : "international","Country":"England"
            "names" : 
            [ 
                { "name": "kumar","Country":"Newzealand"
            "names" : 
            [ 
                { "name": "kumar","Age":"U25"}
            ]
        }
    ]
}

解决方法

试试这个:

db.collection.updateMany(
   {},{ $set: { "teams.$[element].Country": "Republic of India" } },{ arrayFilters: [{ "element.Country": "India" }] }
);
,

试试这个:

db.collection.updateMany({},{
   $set: {
    "teams.$[].Country": "India"
   }
})