返回数组元素和其他字段的总和

时间:2016-05-19 20:42:10

标签: mongodb mongodb-query aggregation-framework

给出以下示例数据集:

[
  {
    _id: 1,
    prices: [1,2,3],
    category: 'stuff'
  },
  {
    _id: 2,
    prices: [4,5,6],
    category: 'stuff'
  },
  {
    _id: 3,
    prices: [7,8,9],
    category: 'misc'
  }
];

如何获取如下所示的数据:

[
  {
    _id: 1,
    prices: 6,
    category: 'stuff'
  },
  {
    _id: 2,
    prices: 15,
    category: 'stuff'
  },
  {
    _id: 3,
    prices: 24,
    category: 'misc'
  }
]

我可以得到这个:

[
  {
    _id: 1,
    prices: 6
  },
  {
    _id: 2,
    prices: 15
  },
  {
    _id: 3,
    prices: 24
  }
]

通过使用这样的东西:

[
  { $unwind: '$prices' },
  { $group: { _id: '$_id', prices: { $sum: '$prices' } } },
  { $project: { prices: 1 } }
]

但我无法弄清楚如何让它包含"类别"。

1 个答案:

答案 0 :(得分:1)

执行此操作的最佳方法是在$sum阶段使用$project累加器运算符的MongoDB 3.2或更高版本。

db.collection.aggregate([
    { "$project": { 
        "price": { "$sum": "$prices" }, 
        "category": "$category" 
    }}
])

产生:

{ "_id" : 1, "category" : "stuff", "price" : 6 }
{ "_id" : 2, "category" : "stuff", "price" : 15 }
{ "_id" : 3, "category" : "misc", "price" : 24 }

在MongoDB版本< = 3.0中,您需要使用$first运算符。

db.collection.aggregate([  
    { $unwind: '$prices' },   
    { $group: { 
        _id: '$_id', 
        prices: { $sum: '$prices' }, 
        category: { '$first': '$category' } 
    }} 
])
相关问题