Combining logical and comparison operators in MongoDB - Time & Space Complexity
When we combine logical and comparison operators in MongoDB queries, we want to know how the time to run the query changes as the data grows.
We ask: How does the query speed change when there are more documents to check?
Analyze the time complexity of the following code snippet.
db.collection.find({
$and: [
{ age: { $gt: 25 } },
{ $or: [
{ status: "A" },
{ score: { $lt: 50 } }
]}
]
})
This query finds documents where the age is greater than 25 and either the status is "A" or the score is less than 50.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each document in the collection against the combined conditions.
- How many times: Once per document, the query engine tests the age, status, and score fields.
As the number of documents grows, the query must check more documents to find matches.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks of age, status, and score |
| 100 | About 100 checks of age, status, and score |
| 1000 | About 1000 checks of age, status, and score |
Pattern observation: The number of operations grows directly with the number of documents.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the number of documents increases.
[X] Wrong: "Using multiple conditions with $and and $or makes the query slower than checking each condition separately."
[OK] Correct: MongoDB checks all conditions together in one pass per document, so combining them does not multiply the work but keeps it proportional to the number of documents.
Understanding how combined logical and comparison operators affect query time helps you explain how databases handle complex filters efficiently.
"What if we added an index on the age field? How would the time complexity change?"