0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Count by Group with Example

Use the MongoDB aggregation pipeline with $group and $sum to count documents by group, like db.collection.aggregate([{ $group: { _id: "$field", count: { $sum: 1 } } }]).
📋

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 count documents by group, think of splitting your data into buckets based on a field's value. Then, count how many items fall into each bucket using $group to group by the field and $sum to add one for each document in that group.
📐

Algorithm

1
Identify the field to group by.
2
Use the aggregation pipeline to group documents by that field.
3
For each group, count the number of documents by summing 1.
4
Return the grouped counts as the result.
💻

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 by 'category' field in a collection with three documents.

1

Group documents by 'category'

Documents: [{category: 'fruit'}, {category: 'vegetable'}, {category: 'fruit'}] grouped into 'fruit' and 'vegetable'.

2

Count documents in each group

'fruit' group has 2 documents, 'vegetable' group has 1 document.

Group (_id)Count
fruit2
vegetable1
💡

Why This Works

Step 1: Grouping with $group

The $group stage collects documents sharing the same value in the specified field into one group.

Step 2: Counting with $sum

Inside $group, $sum: 1 adds 1 for each document in the group, effectively counting them.

🔄

Alternative Approaches

Using $count after $group
mongodb
db.collection.aggregate([
  { $group: { _id: "$category" } },
  { $count: "totalGroups" }
])
This counts how many groups exist, 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" }
)
mapReduce is older and slower than aggregation but can be used for complex cases.

Complexity: O(n) time, O(k) space

Time Complexity

The aggregation scans all n documents once, grouping them by the field, so time is proportional to the number of documents.

Space Complexity

Space depends on the number of unique groups k, as it stores counts for each group.

Which Approach is Fastest?

Aggregation with $group is faster and more memory efficient than mapReduce for counting by group.

ApproachTimeSpaceBest For
Aggregation $group + $sumO(n)O(k)Counting documents by group efficiently
mapReduceO(n)O(k)Complex processing but slower
Aggregation $count after $groupO(n)O(1)Counting number of groups, not documents
💡
Always use aggregation with $group and $sum for efficient counting by group.
⚠️
Forgetting to use $sum: 1 inside $group results in no counts being calculated.