MongoDB: Remove attribute from nested Object Array

Viewed 119

I have to remove an attribute from an deep nested object inside an array of objects.
It looks like this:
Array

I want to unset the IndividualAge only for one specific Period Type Past
for one specific Block with the name "HouseKeepingDamageCost", if it exists.
I have to take care, because the other Objects inside Blocks and
other Periods have also an attribute called "IndividualAge", they can stay.
Can someone help me ? I tried it with $elemMatch without success.

Thanks in advance.

Playgorund with my Data & Query: Mongoplayground

1 Answers

You want to use arrayfilters to do so:

db.collection.update({},
{
  "$unset": {
    "Blocks.$[block].Periods.$[period].IndividualAge": ""
  }
},
{
  "multi": false,
  arrayFilters: [
    {
      "block.Name": "HouseKeepingDamageCost"
    },
    {
      "period.Type": "Past"
    }
  ]
})

Mongo Playground

Related