$or operator behavior in MongoDB - Time & Space Complexity
When using the $or operator in MongoDB queries, it is important to understand how the query time changes as the data grows.
We want to know how the number of checks MongoDB does increases when we add more documents or more conditions inside $or.
Analyze the time complexity of the following MongoDB query using $or.
db.collection.find({
$or: [
{ field1: value1 },
{ field2: value2 },
{ field3: value3 }
]
})
This query finds documents where field1 equals value1 OR field2 equals value2 OR field3 equals value3.
Look at what repeats when MongoDB runs this query.
- Primary operation: Checking each document against each condition inside the
$orarray. - How many times: For each document, MongoDB checks each condition until one matches or all fail.
As the number of documents grows, MongoDB must check more documents. Also, more $or conditions mean more checks per document.
| Input Size (n documents) | Approx. Operations |
|---|---|
| 10 | About 10 x 3 = 30 checks |
| 100 | About 100 x 3 = 300 checks |
| 1000 | About 1000 x 3 = 3000 checks |
Pattern observation: The total checks grow roughly in direct proportion to the number of documents and the number of $or conditions.
Time Complexity: O(n x k)
This means the time grows linearly with the number of documents n and the number of $or conditions k.
[X] Wrong: "Adding more $or conditions does not affect query time much because MongoDB stops at the first match."
[OK] Correct: MongoDB may check multiple conditions per document if earlier conditions fail, so more conditions can increase checks and time.
Understanding how $or affects query time helps you write efficient queries and explain your reasoning clearly in real-world situations.
What if we added indexes on the fields inside the $or conditions? How would the time complexity change?