0
0
MongoDBquery~5 mins

Combining comparison operators in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Combining comparison operators
O(n)
Understanding Time 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.

Scenario Under Consideration

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

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

Explain the growth pattern intuitively.

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 run the query grows linearly with the number of documents in the collection.

Common Mistake

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

Interview Connect

Understanding how combined conditions affect query time helps you explain database performance clearly and shows you know how queries scale with data.

Self-Check

"What if we added an index on price and rating? How would the time complexity change?"