I use the MongoDB aggregation API to aggregate some data daily. The result of this aggregation is of this format:
[
{
aggDate: '2019-05-23',
results: [
{
foo: 0.58,
bar: 0.42
}, {
foo: 0.32,
bar: 0.98
}
]
}
]
The aggregation on the date is fine, but now I would like to aggregate the objects in the results array.
The result of this aggregation should be of the following format:
[
{
aggDate: '2019-05-23',
result: {
foo: 0.45 // avg of all the `foo`, here: (0.58 + 0.32) / 2
bar: 0.7 // avg of all the `bar`, here: (0.42 + 0.98) / 2
}
}
]
My problem here is that the keys foo and bar can change/new fields can be added in results objects. To avoid recoding the query each time it occurs, I want to use some generic way to say to MongoDB
Take this array of objects and reduce it into a single object where each value is the average of the same field in all objects.
I know the $reduce operator exists in MongoDB but I can't figure out how to use it and I am not even sure if it can help me here.