Home > Software design >  Update nested array filed in multiple doc at once
Update nested array filed in multiple doc at once

Time:11-26

I have huge number of records in collection on the below structure.

Here i wanted to update all "floor" field as empty "" ,wherever its "n/a". It should not affect other block which already has value for floor like First Second Floor.

Can someone help on this?

{
    "id" : "181",
    "EID" : "83",
    "History" : [ 
        {
            "aNum" : "12324",
            "dev" : [ 
                {
                    "type" : "",
                    "room" : "Office",
                    "floor" : "Second Floor"
                }, 
                {
                    "type" : "",
                    "room" : "Bedroom",
                    "floor" : "n/a"
                },
                {
                    "type" : "",
                    "room" : "Bedroom",
                    "floor" : "First Floor"
                },
                {
                    "type" : "",
                    "room" : "Bedroom",
                    "floor" : "n/a"
                },
            ]
        }
    ]
}

CodePudding user response:

With arrayFilters and filtered $[<identifier>] operator.

db.collection.update({},
{
  $set: {
    "History.$[].dev.$[dev].floor": ""
  }
},
{
  arrayFilters: [
    {
      "dev.floor": "n/a"
    }
  ],
  multi: true
})

Sample Mongo Playground

  • Related