MongoDB Query to Find Count Per Group
Use the MongoDB aggregation pipeline with
$group stage like db.collection.aggregate([{ $group: { _id: "$fieldName", count: { $sum: 1 } } }]) to find the count per group.Examples
Input[{ category: "fruit" }, { category: "vegetable" }, { category: "fruit" }]
Output[{ _id: "fruit", count: 2 }, { _id: "vegetable", count: 1 }]
Input[{ type: "A" }, { type: "B" }, { type: "A" }, { type: "B" }, { type: "C" }]
Output[{ _id: "A", count: 2 }, { _id: "B", count: 2 }, { _id: "C", count: 1 }]
Input[]
Output[]
How to Think About It
To find the count per group, think of grouping documents by a specific field using
$group. Then, count how many documents fall into each group by summing 1 for each document in that group.Algorithm
1
Identify the field to group by.2
Use the <code>$group</code> stage in aggregation to group documents by that field.3
For each group, count documents by summing 1.4
Return the grouped results with counts.Code
mongodb
db.collection.aggregate([
{ $group: { _id: "$category", count: { $sum: 1 } } }
])Output
[
{ "_id": "fruit", "count": 2 },
{ "_id": "vegetable", "count": 1 }
]
Dry Run
Let's trace counting documents grouped by 'category' field.
1
Group documents by category
Group documents with categories: fruit, vegetable, fruit
2
Count documents in each group
fruit group has 2 documents, vegetable group has 1 document
| category | count |
|---|---|
| fruit | 2 |
| vegetable | 1 |
Why This Works
Step 1: Grouping by field
The $group stage groups documents by the specified field, here category.
Step 2: Counting documents
The $sum: 1 adds 1 for each document in the group, giving the count.
Alternative Approaches
Using $count after $group
mongodb
db.collection.aggregate([
{ $group: { _id: "$category" } },
{ $count: "totalGroups" }
])Counts total number of groups, not documents per group.
Using mapReduce
mongodb
db.collection.mapReduce( function() { emit(this.category, 1); }, function(key, values) { return Array.sum(values); }, { out: "category_counts" } )
Older approach, less efficient than aggregation pipeline.
Complexity: O(n) time, O(k) space
Time Complexity
The aggregation scans all n documents once, grouping them by the field, so time is O(n).
Space Complexity
Space depends on number of groups k, storing counts for each group, so O(k).
Which Approach is Fastest?
Aggregation pipeline with $group is faster and more readable than mapReduce.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Aggregation $group | O(n) | O(k) | Counting per group efficiently |
| mapReduce | O(n) | O(k) | Legacy, complex logic |
| $count after $group | O(n) | O(1) | Counting total groups, not per group |
Always use
$group with $sum: 1 to count documents per group efficiently.Forgetting to use
$sum: 1 inside $group results in no counts being calculated.