2

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

2
  • 1
    add sample data and also the query you tried mongoplayground.net and update the story with the link. Commented Mar 24, 2021 at 14:17
  • @TusharGupta-curioustushar I did add the data & my attempt, please check. Commented Mar 24, 2021 at 14:39

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

this doesn't work for my provided data. mongoplayground.net/p/-Apag7fTtN-
HousekeepingDamageCost is not with a captial K in the data in your link. regardless if it works for my toy example just adapt it to your code and make sure the values match what you intend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.