I have a database with the following documents:
{ name: "John", a: 20, b: 30, c: 40, d: 50 },
{ name: "Rich", a: 20, b: 30, c: 40, d: 50 },
{ name: "Anne", a: 20, b: 30, c: 40, d: 50 },
{ name: "Sam", a: 20, b: 30, c: 40, d: 50 },
I want to calculate the total of hours spent in each of these fields. I accomplished that by:
db.hours.aggregate([{$group: {_id: null, totalA: {$sum: "$a"}, totalB: {$sum: "$b"}, totalC: {$sum: "$c"}, totalD: {$sum: "$d"}}}])
{ "_id" : null, "totalA" : 80, "totalB" : 120, "totalC" : 160, "totalD" : 200 }
Since at some point there will be dozens of fields in each document, is there any easier way to have the total fields be generated dynamically? (as in: check all fields in a document and if they exist in other docs in the collection, sum them all. If they don't exist in other docs, just display that field value as the total). For example, if I have:
{ name: "John", a: 20, b: 30, e: 40, f: 50 },
{ name: "Rich", a: 20, b: 30, c: 40, d: 50 },
{ name: "Anne", a: 20, b: 30, g: 40, h: 50 },
{ name: "Sam", a: 20, b: 30, c: 40, d: 50 },
Should lead to:
{"a" : 80, "b" : 120, "c" : 80, "d" : 100, "e" : 40, "f" : 50, "g" : 40, "h": 50 }
Any suggestions? (without manually writing all the sums as in the aggregate example above)
Thanks!