每个元素的MongoDB对来自多个文档的数组求和 [英] MongoDB sum arrays from multiple documents on a per-element basis
本文介绍了每个元素的MongoDB对来自多个文档的数组求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下文档结构(此示例已简化)
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
.
您的代码应如下所示:
.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屋!
查看全文