$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?"