$lt and $lte for less than in MongoDB - Time & Space Complexity
When using $lt and $lte in MongoDB queries, it's important to know how the query time changes as the data grows.
We want to understand how the number of documents affects the time it takes to find those less than a value.
Analyze the time complexity of the following MongoDB query.
db.products.find({ price: { $lt: 100 } })
.toArray()
.then(results => console.log(results))
.catch(err => console.error(err));
This query finds all products with a price less than 100.
Look at what repeats when the query runs.
- Primary operation: Checking each document's price to see if it is less than 100.
- 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 query time grows in direct proportion to the number of documents in the collection.
[X] Wrong: "Using $lt or $lte always makes the query fast no matter the data size."
[OK] Correct: Without an index, MongoDB must check every document, so the query slows down as data grows.
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?