Why query patterns matter in MongoDB - Performance Analysis
When using MongoDB, the way you write your queries affects how fast they run.
We want to understand how different query patterns change the work the database does as data grows.
Analyze the time complexity of the following MongoDB query pattern.
db.users.find({ age: { $gt: 25 } })
// vs
db.users.find({ $or: [ { age: { $lt: 20 } }, { age: { $gt: 60 } } ] })
The first query finds users older than 25. The second finds users younger than 20 or older than 60.
Look at what repeats when the database runs these queries.
- Primary operation: Scanning documents to check if they match the conditions.
- How many times: Once for each document in the collection or index scanned.
As the number of users grows, the database checks more documents.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the number of documents scanned.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of documents checked.
[X] Wrong: "Adding more conditions with $or always makes the query slower in a complex way."
[OK] Correct: Sometimes $or lets MongoDB use indexes efficiently, so the query can still run in linear time over fewer documents.
Understanding how query patterns affect time helps you write better queries and explain your choices clearly in conversations.
"What if we add an index on the age field? How would the time complexity change?"