简体   繁体   中英

How to perform update query on deeply nested JSON in mongodb?

I have a nested json data structure in mongodb which looks like:

{
    '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
            }
        ]
    }]
}

I want to update the row with "dord": 1 and "tord": 1 and change value of score from 11 to 100 . How do I do this?

What I already tried:

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

Demo - https://mongoplayground.net/p/Mi2HnhzkPpE

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

The filtered positional operator $[] identifies the array elements that match the arrayFilters conditions for an update operation

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM