0
0
MongoDBquery~5 mins

$gt and $gte for greater than in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: $gt and $gte for greater than
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
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 time to find matching documents grows in a straight line as the collection gets bigger.

Common Mistake

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

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?"