MongoDB 以每个元素为基础对来自多个文档的数组求和 [英] MongoDB sum arrays from multiple documents on a per-element basis
问题描述
我有以下文档结构(针对本示例进行了简化)
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]
}
我想得到那些 result
数组的总和,但不是总和,而是一个新的数组,对应于基于元素的原始数组的总和,即
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"}
}
}
]
)
这给了我
[ { _id: sdfsdf, results: 25 },
{ _id: asdref, results: 30 } ]
但我不知道如何获得每个元素的总和
but I can't figure out how to get the sum of each element
推荐答案
您可以使用 includeArrayIndex.
那么你应该改变$unwind
.
你的代码应该是这样的:
Your code should be like this:
.aggregate(
[
{
"$unwind" : { path: "$result", includeArrayIndex: "arrayIndex" }
},
{
"$group": {
"_id": "$arrayIndex",
"results" : { "$sum" : "$result"}
}
},
{
$sort: { "_id": 1}
},
{
"$group":{
"_id": null,
"results":{"$push":"$results"}
}
},
{
"$project": {"_id":0,"results":1}
}
]
)
这篇关于MongoDB 以每个元素为基础对来自多个文档的数组求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!