Combining comparison operators in MongoDB - Time & Space Complexity
When we combine comparison operators in MongoDB queries, it affects how many documents the database checks.
We want to understand how the work grows as the data size grows when using these combined conditions.
Analyze the time complexity of the following code snippet.
db.products.find({
price: { $gt: 10, $lt: 50 },
rating: { $gte: 4 }
})
This query finds products with price greater than 10 and less than 50, and rating at least 4.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning documents to check if they meet all combined conditions.
- How many times: Each document is checked once against all conditions.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of documents.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of documents in the collection.
[X] Wrong: "Combining multiple comparison operators makes the query run faster because it narrows results."
[OK] Correct: While it narrows results, the database still checks each document to see if it matches all conditions, so the work grows with data size.
Understanding how combined conditions affect query time helps you explain database performance clearly and shows you know how queries scale with data.
"What if we added an index on price and rating? How would the time complexity change?"