繁体   English   中英

MongoDB 对数组中对象的聚合求和使其工作

[英]MongoDB Aggregation Sum on Objects in Array make it work

{ "id": 1, "stats": [ { "number": 100, "year": 2014 }, { "number": 200, "year": 2015 } ] }

我想用 arrays 将这个数字相加,我累了但没有得到它,应该给我 300

db.test.aggregate([
  {$project: 
    {totalSum: 
      {$reduce: 
        {input:'$stats', initialValue:0, in: {$sum: '$stats.number'}}
      }
    }
  }
  ])

您基本上只想添加一个包含总和的字段(您可以使用 $addFields 或 $projects),然后您想将给定的数组减少为单个值,这正是 $reduce 阶段所做的。 https://docs.mongodb.com/manual/reference/operator/aggregation/reduce/

reduce 阶段需要 3 个参数:'input' 需要对数组的引用,'initialValue' 您可以将其视为累加器变量,对于最后一个参数,'in' 需要您想要存储在该累加器中的确切内容多变的。 在这种情况下,您想总结 '$stats.number'

希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM