anr1234
anr1234

Reputation: 105

Need one aggregation query to do $match, $group and return count of matching elements and count of all elements in each group

I have a mongodb collection as follows: {color:'blue', category:'A', .....} {color:'yellow', category:'A',....} {color:'blue', category:'B',......} ... ....

A query like: db.collection.aggregate([{$match:{color:'blue'}}, {$group:{_id:"$category", num:{$sum:1}}}])

returns Number of documents with color:'blue' for each category.

Now, I want to also get the total number of documents in each category - in the same aggregation query. This is so as to avoid an extra query to the mongodb server on a very large database. As it is the first query takes more than a few minutes to complete. Adding another query will almost duplicate the work for the database server (grouping and counting again) and therefore take much longer. Is this possible?

If not, is there a single API call to merge two AggregationOutput results on a specified key field?

Thanks.

Upvotes: 2

Views: 1448

Answers (1)

Asya Kamsky
Asya Kamsky

Reputation: 42352

Here is how to do it:

db.collection.aggregate([{$group:{_id:"$category", 
                     num:{$sum:1}, 
                     blues:{$sum:{$cond:[{$eq:["$color","blue"]}, 1, 0]}}
}}]

Upvotes: 0

Related Questions