This is the sample collection:
{'f1': 10, '_id': 1, 'key': 'g', 'items': [{'i1': 10}, {'i1': 10}, {'i1': 10}]}
{'f1': 10, '_id': 2, 'key': 'g', 'items': [{'i1': 10}, {'i1': 10}, {'i1': 10}]}
{'f1': 77, '_id': 3, 'key': 'g', 'items': [{'i1': 10}, {'i1': 10}, {'i1': 10}]}
I want a formula like: $sum(f1 + Σ[items.i1]) to be computed on the above collection. Following is what I could come up with (in pymongo):
db.collec.aggregate([
{ "$unwind" : "$items"},
{ "$group" : {
"_id" : {"key": "$key", "id": "$_id"},
"matches" : { "$sum" : "$items.i1" },
"extra" : { "$sum" : "$f1" },
"count" : {"$sum": 1}
}},
{ "$group": {
"_id" : "$_id.key",
"finalSum":{ "$sum":
{ "$add": ["$matches", {"$divide":["$extra", "$count"]}]}}}}
]);
Output:
{'finalSum': 187.0, '_id': 'g'}
Although this gives correct output, I hope there's a better, simpler solution for this: Any help highly appreciated.