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
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"
}
]
})