我有以下文档结构(针对此示例进行了简化)
{
_id : ObjectId("sdfsdf"),
result : [1, 3, 5, 7, 9]
},
{
_id : ObjectId("asdref"),
result : [2, 4, 6, 8, 10]
}
我想得到这些的总和result
数组,但不是总和,而是一个与元素基础上原始数组之和相对应的新数组,即
result : [3, 7, 11, 15, 19]
我在这里搜索了无数的问题,其中一些问题很接近(例如this one, this one, and this one),但我还不能完全到达那里。
我可以得到每个数组的总和
aggregate(
[
{
"$unwind" : "$result"
},
{
"$group": {
"_id": "$_id",
"results" : { "$sum" : "$result"}
}
}
]
)
这给了我
[ { _id: sdfsdf, results: 25 },
{ _id: asdref, results: 30 } ]
但我不知道如何获得每个元素的总和