Hello, I want to do something that seemed trivial to me, but I can’t find a way to do it in mongodb aggregations. I’m using Compass to make my aggregations.
Let’s say I have this aggregation
$group: {
{
_id: '$region',
"customer_average_income": {
$avg: '$customer_income'
},
"customer_average_expenses": {
$avg: '$customer_expenses'
},
"customer_average_something": {
$avg: '$customer_something'
}
}
}
It works fine, but I have to hard-code the fields of which I want to calculate the average, manually. Let’s say I have many of those fields of which I want to calculate the average, how do I achieve an equivalent aggregation where I can just pass the field as a variable?
Something like this, but $map cannot be used in $group aggregation:
$group: {
{
_id: '$region',
"$map": {
input: '$$ROOT',
in: {$avg: '$$ROOT'}
}
}
What am I missing? Any help will be very appreciated, thank you.