Reputation: 342
I have a collection called Students.
Documents have a field house
which contains a string value, for example:
'Gryffindor'
, 'Hufflepuff'
, 'Ravenclaw'
, 'Slytherin'
I am displaying the count of the students in each house.
For that I'm doing something like this:
G = Students.find({ house: 'Gryffindor' }).count();
H = Students.find({ house: 'Hufflepuff' }).count();
R = Students.find({ house: 'Ravenclaw' }).count();
S = Students.find({ house: 'Slytherin' }).count();
and displaying.
Is there a way that this could be done in a single query?
Upvotes: 3
Views: 1054
Reputation:
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.
Upvotes: 0
Reputation: 4055
You can do it in a single query using mongo aggregation.
Students.aggregate([
{
$group : {
_id : "$house",
count: { $sum: 1 }
}
}
])
Upvotes: 3