countDocuments method in MongoDB - Time & Space Complexity
When using MongoDB's countDocuments method, it's important to know how the time it takes grows as the data grows.
We want to understand how the number of documents affects the time to count them.
Analyze the time complexity of the following code snippet.
const count = await db.collection('users').countDocuments({ age: { $gte: 18 } });
console.log(`Number of adult users: ${count}`);
This code counts how many users are 18 years old or older in the 'users' collection.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning documents or index entries to check if they match the filter.
- How many times: Once for each document or index entry scanned.
As the number of documents grows, the time to count them grows roughly in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows roughly in direct proportion to the number of documents scanned.
Time Complexity: O(n)
This means the time to count documents grows linearly with the number of documents checked.
[X] Wrong: "Counting documents is always instant no matter how many there are."
[OK] Correct: The database must check each document or index entry to see if it matches, so more documents usually mean more time.
Understanding how counting scales helps you explain database performance clearly and shows you know how data size affects operations.
"What if we added an index on the 'age' field? How would the time complexity of countDocuments change?"