$count accumulator in MongoDB - Time & Space Complexity
When using the $count accumulator in MongoDB, we want to understand how the time it takes grows as the data size grows.
We ask: How does counting documents scale when the collection gets bigger?
Analyze the time complexity of the following code snippet.
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $count: "totalCount" }
])
This code filters orders with status "completed" and then counts how many such orders exist.
- Primary operation: Scanning each document to check if it matches the filter.
- How many times: Once for each document in the collection or matching subset.
As the number of documents grows, the time to check each document and count matching ones grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the number of documents to check.
Time Complexity: O(n)
This means the time to count grows in a straight line with the number of documents.
[X] Wrong: "Counting documents with $count is instant no matter how many documents there are."
[OK] Correct: MongoDB must look at each document to see if it matches before counting, so more documents mean more work.
Understanding how counting scales helps you explain database performance clearly and shows you know how data size affects queries.
"What if we added an index on the status field? How would the time complexity of counting change?"
Practice
$count accumulator do in a MongoDB aggregation pipeline?Solution
Step 1: Understand the purpose of
The$count$countaccumulator is used inside the$groupstage to count how many documents belong to each group.Step 2: Compare with other accumulators
Unlike$sum,$max, or$avg,$countdoes not operate on field values but counts documents.Final Answer:
Counts the number of documents in each group -> Option AQuick Check:
$count= document count [OK]
- Thinking $count sums field values
- Using $count outside $group stage
- Expecting $count to take arguments
$count in a $group stage?Solution
Step 1: Recall
The$countsyntax$countaccumulator does not take any arguments inside its braces; it should be empty:{ $count: {} }.Step 2: Check each option
Options A, B, and D incorrectly pass a field name or string to$count, which is invalid syntax.Final Answer:
{ $group: { _id: "$category", total: { $count: {} } } } -> Option DQuick Check:
Empty braces for $count = correct syntax [OK]
- Passing a field name inside $count
- Using empty string instead of empty braces
- Confusing $count with $sum syntax
{ "category": "A" }, { "category": "B" }, { "category": "A" }What will be the output of this aggregation?
[ { $group: { _id: "$category", count: { $count: {} } } } ]Solution
Step 1: Understand $count usage
The$countaccumulator is not valid inside a$groupstage. It is a separate pipeline stage used to count total documents, not per group.Step 2: Correct way to count documents per group
To count documents per group, use$sum: 1inside$group, not$count.Step 3: Result of using
Using$countinside$group$countinside$groupcauses a syntax error.Final Answer:
SyntaxError: $count requires a field name -> Option AQuick Check:
$countis a pipeline stage, not an accumulator [OK]
- Using $count inside $group
- Expecting $count to count per group
- Confusing $count accumulator with $count stage
[ { $group: { _id: "$type", total: { $count: "$amount" } } } ]Solution
Step 1: Check $count usage
The$countaccumulator does not accept any arguments; passing "$amount" is invalid syntax.Step 2: Verify other parts
The _id field and pipeline structure are correct; no $match is required before $group, and $count is inside aggregation.Final Answer:
Using $count with a field argument is invalid -> Option CQuick Check:
$count must have empty braces {} [OK]
- Passing a field name to $count
- Thinking $count needs $match before $group
- Confusing $count with $sum
$count to achieve this?Solution
Step 1: Count orders per customer
Since$countis not valid inside$group, use$sum: 1to count documents per group.Step 2: Filter customers with more than 2 orders
Use$matchafter grouping to filter customers withorderCountgreater than 2.Final Answer:
[ { $group: { _id: "$customer", orderCount: { $sum: 1 } } }, { $match: { orderCount: { $gt: 2 } } } ] -> Option BQuick Check:
Use $sum:1 to count per group, then filter [OK]
- Using $count inside $group
- Passing a field to $count
- Filtering before counting
Ready to prove it?
Pass the test and this pattern moves unknown
