【问题标题】:How to perform update query on deeply nested JSON in mongodb?如何在 mongodb 中对深度嵌套的 JSON 执行更新查询?
【发布时间】:2021-03-28 21:14:52
【问题描述】:

我在 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": 1"tord": 1 更新行并将score 的值从11 更改为100。我该怎么做?

我已经尝试过的:

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

【问题讨论】:

    标签: arrays database mongodb mongodb-query


    【解决方案1】:

    演示 - 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
      ]
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-10
      • 2021-06-25
      • 2013-08-12
      • 1970-01-01
      相关资源
      最近更新 更多