Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
mongo remove/pull grandchild item in deeply nested array

I have a deeply nested document of family members

[{
  "id": 1,
  "children" : [
    {
        "id" : 1,
        "grandChildren": [
            {
                "id" : 1,
                "toys": [
                    {
                        "id":1
                    }
                ]

            }
        ]
    },
    {
        "id" : 2,
        "grandChildren": [
            {
                "id" : 1,
                "toys": [
                    {
                        "id":1
                    }
                ]

            }
        ]
    }
  ]
}]

I'm told the toys are unique to the grandchildren, which are also unique, etc, but there's a chance they're not and I'd like to make absolutely sure when I remove them I'm only removing them for the specific grandchild of the specific child etc,

I have a query that can pull all toys matching the id I was wondering how I can be more specific and burrow down through the specific parents?

db.family.updateOne(
 {"id": "1"}, 
 {"$pull" : 
   { "children.$[].grandChildren.$[].toys" : 
     {"id" : "1"}
   }
 })

All help appreciated

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

What you want to do is use arrayFilters like so:

db.collection.updateOne({
  "id": "1"
},
{
  "$pull": {
    "children.$[child].grandChildren.$[grandChild].toys": {
      "id": "1"
    }
  }
},
{
  arrayFilters: [
    {
      "child.id": "1"
    },
    {
      "grandChild.id": "1"
    }
  ]
})

Mongo Playground

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!