MongoDB 基于每个元素对来自多个文档的数组求和 [英] MongoDB sum arrays from multiple documents on a per-element basis

查看:12
本文介绍了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.

你的代码应该是这样的:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆