0
0
MongoDBquery~5 mins

$lt and $lte for less than in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: $lt and $lte for less than
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of documents grows, the query checks more prices.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of checks grows directly with the number of documents.

Final Time Complexity

Time Complexity: O(n)

This means the query time grows in direct proportion to the number of documents in the collection.

Common Mistake

[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.

Interview Connect

Understanding how simple comparison queries scale helps you explain database performance clearly and confidently.

Self-Check

What if we added an index on the price field? How would the time complexity change?