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

查看:19
本文介绍了数组中对象的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天全站免登陆