2
votes

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

1 Answers

3
votes

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

}}    
)