You have the right general idea about the flow, but your structure is slightly off.
Your first stage, $match the conditions to qualify to be counted is fine.
match = {$match: {
"meta.active": true,
"meta.client.id": 1,
"data.attributes.lang": "en",
"data.attributes.geo": "us"
}
Your next stage is $group, as it should be, but you are not quite grouping around the correct key. Since you want to get totals over all the qualified documents, you should be grouping with _id
as a constant, and doing $sum
of 1 or 0 depending on whether the conditional evaluations to true or not.
group = {$group: {
_id: null,
querisAddedSinceLastWeek : { $sum : {$cond: [
{ $gt : [ meta.created, ISODate("2014-03-30 12:27:50") ] },
1, 0 ] }
},
queriesWithExpectedResultsCount: { $sum:
{ $eq : [ data.expectedResults, null ] },
1, 0 ] }
},
totalActiveQueriesCount: { $sum : 1 }
} }
Your map function has a lot of unnecessary (redundant) conditions, it's usually better to express what you actual want - but what it's currently doing is summing up all the active queries, and also getting a sum of queries since last week, and ones that have null data.expectedResults.
Full aggregate, with above two stages defined:
db['ARTDocument.dev'].aggregate( match, group );