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!