$nor operator behavior in MongoDB - Time & Space Complexity
We want to understand how the time needed to run a MongoDB query using the $nor operator changes as the data grows.
Specifically, how does checking multiple conditions with $nor affect the work the database does?
Analyze the time complexity of the following code snippet.
db.collection.find({
$nor: [
{ age: { $lt: 30 } },
{ status: "inactive" }
]
})
This query finds documents where age is not less than 30 and status is not "inactive".
Look at what repeats when the query runs.
- Primary operation: Checking each document against all conditions inside the
$norarray. - How many times: Once per document in the collection.
As the number of documents grows, the database checks more documents.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 document checks |
| 100 | About 100 document checks |
| 1000 | About 1000 document checks |
Pattern observation: The work 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 $nor makes the query faster because it excludes conditions early."
[OK] Correct: The database still checks each document against all $nor conditions, so it does not skip work just because of $nor.
Understanding how query operators like $nor affect performance helps you write better database queries and explain your choices clearly.
What if we added indexes on the fields inside the $nor conditions? How would the time complexity change?