Search code examples
arraysmongodbmongoosemongodb-querypymongo

Update nested array field for multiple docs at once


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

Here I want to update all floor fields as an empty string "", wherever it's "n/a". It should not affect other blocks which already have value for the floor like the 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"
                },
            ]
        }
    ]
}

Solution

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

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

    Sample Mongo Playground