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?
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 $function
Use $function
and inside the body define a recursive function. Would be this one:
db.collection.aggregate([
{
$set: {
reply: {
$function: {
body: function (doc, field) {
function removeField(obj) {
for (let obj in doc) {
for (let prop in obj) {
if (prop === field)
delete obj[prop];
else if (typeof obj[prop] === 'object')
removeField(obj[prop]);
}
}
}
removeField(doc);
return doc;
},
args: ["$reply", "tag"],
lang: "js"
}
}
}
}
])