MongoDB - How can I use multiple groups in an aggregation pipeline?

吃可爱长大的小学妹 提交于 2019-12-11 02:53:00

问题


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?

Thanks!


回答1:


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 ] }}

}}    
)


来源:https://stackoverflow.com/questions/21028018/mongodb-how-can-i-use-multiple-groups-in-an-aggregation-pipeline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!