How to get the count of multiple queries on one collection in only one query? How to get the count of multiple queries on one collection in only one query? mongodb mongodb

How to get the count of multiple queries on one collection in only one query?


You can do it in a single query using mongo aggregation.

Students.aggregate([    {         $group : {            _id : "$house",            count: { $sum: 1 }        }    }])


If you already have all the data locally, you could do it using an aggregation, either using the mongo one (like Volodymyr pointed out) or underscore/lodash's countBy method.

In the server it always works because all data is always present, but for this to work on client (display the actual count) you should have all users published, which might not be the best practice and even impossible for large applications.

In that case, you should probably use a method (which will return the non-reactive counts), create a separate counts collection and keeping it up to date or even use the low-level meteor publication API to publish a reactive count.