Home > Enterprise >  Mongo Update key nested in array if exists
Mongo Update key nested in array if exists

Time:11-22

I have a similar structure. In every level there is a "changed" key and inside it can exists or not an array which nested value is recursive.

{
"id" : 1,
"changed" : false,
"level_2" : [ 
    {
        "changed" : false
    }, 
    {
        "changed" : false,
        "level_3" : [ 
            {
                "changed" : false
            }, 
            {
                "changed" : false,
                "level_4" : [ 
                    {
                        "changed" : false
                    }
                ]
            }
        ]
    }
  ]
}

I have to update all changed keys to true.

I tried this

db.getCollection.update(
{ "id": 1 }, 
{ "$set": { "changed": true, 
    "level_2.$[].changed": true, 
    "level_2.$[].level_3.$[].changed": true,  
    "level_2.$[].level_3.$[].level_4.$[].changed": true} }
)

but it throws The path 'level_2.0.level_3' must exist in the document in order to apply array updates.

CodePudding user response:

You need arrayFilters to check there is level_3 and/or level_4 (via $exists). If yes, then process to update the nested array fields for level_3 and/or level_4.

db.collection.update({
  "id": 1
},
{
  "$set": {
    "changed": true,
    "level_2.$[].changed": true,
    "level_2.$[levelThree].level_3.$[].changed": true,
    "level_2.$[levelThree].level_3.$[levelFour].level_4.$[].changed": true
  }
},
{
  arrayFilters: [
    {
      "levelThree.level_3": {
        $exists: true
      }
    },
    {
      "levelFour.level_4": {
        $exists: true
      }
    }
  ]
})

Sample Mongo Playground

  • Related