$and operator behavior in MongoDB - Time & Space Complexity
When using the $and operator in MongoDB queries, it is important to understand how the query time grows as we add more conditions.
We want to know how the number of conditions affects the work MongoDB does to find matching documents.
Analyze the time complexity of the following MongoDB query using $and.
db.collection.find({
$and: [
{ age: { $gt: 25 } },
{ status: "active" },
{ score: { $gte: 70 } }
]
})
This query finds documents where age is greater than 25, status is "active", and score is at least 70.
Look at what MongoDB does internally to process this query.
- Primary operation: MongoDB checks each condition in the
$andarray for every document it considers. - How many times: For each document, it evaluates all conditions one by one until one fails or all pass.
As the number of conditions in $and grows, MongoDB must check more conditions per document.
| Number of Conditions (n) | Approx. Checks per Document |
|---|---|
| 3 | 3 checks |
| 10 | 10 checks |
| 100 | 100 checks |
Pattern observation: The work grows linearly with the number of conditions because each condition is checked in order.
Time Complexity: O(n)
This means the time to evaluate the $and conditions grows directly in proportion to how many conditions there are.
[X] Wrong: "Adding more conditions inside $and does not affect query time much because MongoDB is fast."
[OK] Correct: Each condition adds extra checks for every document, so more conditions mean more work and longer query time.
Understanding how $and affects query time helps you write efficient queries and explain your reasoning clearly in interviews.
"What if we replaced $and with $or? How would the time complexity change?"