Query filter syntax in MongoDB - Time & Space Complexity
When we use query filters in MongoDB, we want to know how the time to find data changes as the data grows.
We ask: How does the filter affect the work MongoDB does as the collection gets bigger?
Analyze the time complexity of the following code snippet.
db.users.find({ "age": { "$gt": 25 } })
This code finds all users older than 25 years in the users collection.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning documents to check if the age is greater than 25.
- How many times: Once for each document in the collection until all are checked or results found.
As the number of users grows, MongoDB checks more documents to find matches.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the number of documents.
Time Complexity: O(n)
This means the time to find matching documents grows linearly as the collection size grows.
[X] Wrong: "Using a filter always makes the query very fast regardless of data size."
[OK] Correct: Without an index, MongoDB must check each document, so the time grows with data size.
Understanding how filters affect query time helps you explain how databases handle searches as data grows, a useful skill in many real projects.
"What if we added an index on the age field? How would the time complexity change?"