首页 > 解决方案 > 如何在 mongodb 中对深度嵌套的 JSON 执行更新查询?

问题描述

我在 mongodb 中有一个嵌套的 json 数据结构,如下所示:

{
    'tid': 1,
    'matches': [{
        'dord': 1,
        'matches': [{
                'tord': 1,
                'score': 11
            },
            {
                'tord': 2,
                'score': 12
            }
        ]
    },
    {
        'dord': 2,
        'matches': [{
                'tord': 1,
                'score': 21
            },
            {
                'tord': 2,
                'score': 22
            }
        ]
    }]
}

我想用"dord": 1and更新行"tord": 1并将值score11更改为100。我该怎么做呢?

我已经尝试过的:

db.collection.update({'tid': 1}, {'matches': {$elemMatch: {'dord': 1}}}, {'matches': { $elemMatch: {'tord': 1}}}, {'score': 100})

标签: arraysdatabasemongodbmongodb-query

解决方案


演示 - https://mongoplayground.net/p/Mi2HnhzkPpE

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

过滤的位置运算符 $[] 标识与更新操作的 arrayFilters 条件匹配的数组元素

db.collection.update({ "tid": 1 },
{ $set: { "matches.$[m].matches.$[t].score": 100  } },
{
  arrayFilters: [
    { "m.dord": 1 }, // to match where dord = 1
    { "t.tord": 1, "t.score": 11 } // and where tord = 1 and score = 11
  ]
})

推荐阅读