I have some data in mongoDB and i want to group and sum it in object key - value:
{
'_id': '1',
'value': {
A: 1,
B: 2,
C: 3
}
},
{
'_id': '2',
'value': {
B: 2,
C: 3
}
}
I need to group by keys name and sum the value of each key - that value. For the example above the result would be:
{
'_id': 'A',
'total': 1
},
{
'_id': 'B',
'total': 4
},
{
'_id': 'C',
'total': 6
}
Query
object to array
is used*if your fields are unknown its not good idea, its best the schema to be known, even if some fields can be missing, but not knowing the schema causes many problems while querying
aggregate(
[{"$set": {"value": {"$objectToArray": "$value"}}},
{"$unwind": "$value"},
{"$group": {"_id": "$value.k", "count": {"$sum": "$value.v"}}}])