数组中对象的MongoDB聚合总和 [英] MongoDB Aggregation Sum on Objects in Array

查看:79
本文介绍了数组中对象的MongoDB聚合总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多关于如何求和数组中数组对象的属性的答案,但是我试图跨文档对一个数组中对象的单个属性求和.例如,给定此文档结构:

I've seen a lot of answers on how to sum properties of objects in arrays within the array, but I'm trying to sum individual properties on an object in an array across documents. For example, given this document structure:

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


{
   "id": 2,
   "stats": [
     {
       "number": 50,
       "year": 2014
     },
     {
       "number": 75,
       "year": 2015
     }
]
}

所需的输出将是:

{
   "stats": [
     {
       "number": 150,
       "year": 2014
     },
     {
       "number": 275,
       "year": 2015
     }
}

我不想对2014和2015的number属性求和,我想对两个文档在2014年进行求和.

I don't want to sum the number property of 2014 and 2015, I want to sum it across 2014 for both documents.

推荐答案

db.test.aggregate([
   {  $unwind: "$stats" },
   {
        $group: {
            _id:"$stats.year",
            number:{$sum:"$stats.number"}
        }
    },
    { 
        $group: {
          _id: 0,  
          stats:{ $push:  {year:"$_id",number:"$number"}}
        }
    },
    {  
        $project:{stats:1,_id:0}
    } ])

这篇关于数组中对象的MongoDB聚合总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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