I have the following document structure (simplified for this example)
{
_id : ObjectId("sdfsdf"),
result : [1, 3, 5, 7, 9]
},
{
_id : ObjectId("asdref"),
result : [2, 4, 6, 8, 10]
}
I want to get the sum of those result
arrays, but not a total sum, instead a new array corresponding to the sum of the original arrays on an element basis, i.e.
result : [3, 7, 11, 15, 19]
I have searched through the myriad questions here and a few come close (e.g. this one, this one, and this one), but I can't quite get there.
I can get the sum of each array fine
aggregate(
[
{
"$unwind" : "$result"
},
{
"$group": {
"_id": "$_id",
"results" : { "$sum" : "$result"}
}
}
]
)
which gives me
[ { _id: sdfsdf, results: 25 },
{ _id: asdref, results: 30 } ]
but I can't figure out how to get the sum of each element
Erkan Demirel :
You can use includeArrayIndex if you have 3.2 or newer MongoDb.\n\nThen you should change $unwind.\n\nYour code should be like this:\n\n.aggregate(\n [\n {\n \"$unwind\" : { path: \"$result\", includeArrayIndex: \"arrayIndex\" }\n },\n {\n \"$group\": {\n \"_id\": \"$arrayIndex\",\n \"results\" : { \"$sum\" : \"$result\"}\n }\n },\n { \n $sort: { \"_id\": 1}\n },\n {\n \"$group\":{\n \"_id\": null,\n \"results\":{\"$push\":\"$results\"}\n } \n },\n {\n \"$project\": {\"_id\":0,\"results\":1}\n }\n ]\n)\n",
2016-02-18T12:51:17