I am trying to find the way to remove the properties from nested object array by using aggregate framework in MongoDB but I still can’t find any solution for my issue.
I have an nested object array like below:
{
_id: '...',
name: 'Warwick',
description: 'Warwick desc...',
reply: [
{
_id: '...',
tag: 'champ',
name: 'Warwick child',
description: 'Warwick desc...',
reply: [
{
_id: '...',
tag: 'champ',
name: 'Warwick child',
description: 'Warwick desc...',
reply: []
},
...etc...
]
},
...etc...
]
}
The desired results:
{
_id: '...',
name: 'Warwick',
description: 'Warwick desc...',
reply: [
{
_id: '...',
name: 'Warwick child',
description: 'Warwick desc...',
reply: [
{
_id: '...',
name: 'Warwick child',
description: 'Warwick desc...',
reply: []
},
...etc...
]
},
...etc...
]
}
What I need is remove tag
property from each element in array. I tried using $unset
but it doesn’t seem to work in this case. How can I solve this problem?
2
Answers
I assume the depth of
reply
fields is not determined. I don’t think you can do it purely in aggregation framework – but almost, using $functionUse
$function
and inside the body define a recursive function. Would be this one:Here are a few ways to remove properties from nested object arrays in MongoDB using the aggregate framework. One way is to use the $pull operator, other is to use
unset
operator.The
$pull
operator allows you to remove a specific field from a document.You can also use the
unset
operator. Which does the same thing.