I have a BlogPost model, and two of its attributes are draft: Boolean and user: String. Is it possible to get the following counts in one query using mongo's aggregation framework with Mongoose?
BlogPost.count({ user: userID }, function(err, response() {});
BlogPost.count({ user: userID, draft: true }, function(err, response() {});
The $cond operator is a ternary operator that evaluates a conditional expression to true/false and returns either the second or third arguments respectively depending on the evaluation. Your field in this case is either boolean true/false, so there is no need to test with another operator. You implement this inside the $sum:
BlogPost.aggregate(
[
{ "$group": {
"_id": null,
"total_count": { "$sum": 1 },
"draft_count": { "$sum": { "$cond": [ "$draft", 1, 0 ] } }
}
],
function(err,results) {
}
);
Passing in null to the _id value of group means that you are not "grouping" on any specific document key but are grouping all of the documents in the collection.