I have a MongoDB collection with documents that look like:
{
'_id': 'doc1',
'store_A': {'apples': 50, 'oranges':20},
'store_B': {'oranges': 15}
}
{
'_id': 'doc2',
'store_A': {'oranges':10},
'store_B': {'apples': 15}
}
How can I write an aggregation command to give me the total number of fruits for each store across all documents in the collection WITHOUT enumerating all allowed kinds of fruit?
The result should look like:
{
'_id': 'Result',
'store_A_total': {'apples': 50, 'oranges': 30},
'store_B_total': {'apples': 15, 'oranges': 15}
}
This query works, but all the fruit types must be specified explicitly:
db.collection.aggregate(
{'$group': {'_id': 'Result',
'store_A_apples': {'$sum': '$Store_A.apples'},
'store_A_oranges': {'$sum': '$store_A.oranges'},
'store_B_apples': {'$sum': '$store_B.apples'},
'store_B_oranges': {'$sum': '$store_B.oranges'}
}},
{'$project': {
'store_A': {'apples': '$store_A_apples','oranges': '$store_A_oranges'},
'store_B': {'apples': '$store_B_apples','oranges': '$store_B_oranges'}
}})
Is there a better way to structure these documents to facilitate this type of query?