MongoDB-如何在聚合管道中使用多个组? [英] MongoDB - How can I use multiple groups in an aggregation pipeline?

查看:81
本文介绍了MongoDB-如何在聚合管道中使用多个组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对文档集合进行一些汇总.这些文档如下所示:

I am trying to perform some aggregation on a collection of documents. The documents look like this:

{name: "Sara", brandId: 1, count: 2 day:1/6/2014}//day value is ISODate
{name: "Sally", brandId: 1, count: 5 day:1/7/2014} 
{name: "Mike", brandId: 1, count: 2, day: 1/8/2014} 
{name: "Bob", brandId: 1, count: 4 day: 1/8/2014}
{name: "Joe", brandId: 1, count: 5 day:1/8/2014}

我想做的是获取所有计数"值的总和.然后,我想按日期范围对文档进行分组,并获得第二次分组的总和.所以我想做这样的事情:

What I am trying to do is get the aggregate sum of all the 'count' values. Then I would like to group the documents by a date range and get the aggregate sum of the second grouping. So I would like to do something like this:

db.people.aggregate(
     { $match : { BrandId : 4 } },  
     { $group : {
        _id : "$brandId",
        TotalCount : { $sum : "$count" } //get the sum of all document 'count'       
    }},
    {$match: {
    'Day': { $gte: new Date(2014, 0, 6), 
         $lte: new Date(2014, 0, 8)}
    }},
    { $group : {
      _id : "$BrandId",
      countInTimeRange : { $sum : "$count" } //get the sum of 'count' within time range
    }}
    )

因此,我想获取所有匹配文档的计数,然后按日期范围过滤它们,并获取过滤后的日期范围匹配文档的总和. 这可能吗?

So I would like to get the count for all the matching documents, then filter them by a date range and get the aggregate sum of the filtered date range matched documents. Is this possible?

谢谢!

推荐答案

我能够在$ group操作中使用$ cond找到解决方案.

I was able to find a solution using $cond in my $group operation.

db.project.aggregate(
{ $match : { brandId : 4 } },
{ $project : {
    _id : 0,
    brandId : 1,
    count : 1,
    day : 1}
},  
 { $group : {
    _id : "$brand",
    TotalCount : { $sum : "$count" },        
    countInTimeRange : {$sum: { $cond: [ { $and: [{$gte: [ "$day", new Date(2014, 0, 6) ] }, {$lte: [ "$day", new Date(2014, 0, 8) ] }] }, "$count", 0 ] }}

}}    
)

这篇关于MongoDB-如何在聚合管道中使用多个组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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