Afterwards an aggregation in mongodb
I get this results:
[
my_arr:[
{
id: ObjectId('618f7ef057c2923be10d1111')
//other stuff
},
{},
{},
]
]
Is there a way to remove the empty object directly in the aggregation? or it is necessary to do it server side? I get that after doing an unwind and a group.
CodePudding user response:
You can add a new aggregation stage ( $project
, $set
or $addFields
) with $filter
like this:
{
"$project": {
"my_arr": {
"$filter": {
"input": "$my_arr",
"as": "a",
"cond": {
"$ne": [
"$$a",
{}
]
}
}
}
}
}
This filter get only objects into the array where the object itself is not empty (i.e. is not {}
)
Example here
Also $set example and $addFields example
Also, you can use $$this
to refer the object instead of value from as
. Example here