$gt and $gte for greater than in MongoDB - Time & Space Complexity
When we use $gt or $gte in MongoDB queries, we want to find documents with values greater than a number.
We ask: How does the time to find these documents grow as the collection gets bigger?
Analyze the time complexity of the following code snippet.
db.products.find({ price: { $gt: 100 } })
// or
db.products.find({ price: { $gte: 100 } })
This code finds all products with a price greater than (or equal to) 100.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning documents to check the price field.
- How many times: Once for each document in the collection if no index is used.
As the number of documents grows, the query checks more prices.
| 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 find matching documents grows in a straight line as the collection gets bigger.
[X] Wrong: "Using $gt or $gte always makes queries fast because they are simple comparisons."
[OK] Correct: Without an index on the field, MongoDB must check every document, so the query time grows with collection size.
Understanding how simple comparison queries scale helps you explain database performance clearly and confidently.
"What if we added an index on the price field? How would the time complexity change?"