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
}
2
Answers
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
Playmongo
Here’s how to do this with PHP, I’m not sure if there’s a more efficient way to do it on the DB level. But this does the trick, you might need to wrap your json keys with a quotation first ("A": instead of A:)