$eq for equality in MongoDB - Time & Space Complexity
When we use $eq in MongoDB, we want to find documents where a field matches a specific value.
We ask: How does the time to find these documents grow as the collection gets bigger?
Analyze the time complexity of the following code snippet.
db.collection.find({ age: { $eq: 25 } })
This query finds all documents where the age field equals 25.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each document's
agefield to see if it equals 25. - How many times: Once for each document in the collection if no index is used.
As the collection grows, the number of documents to check grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of documents.
Time Complexity: O(n)
This means the time to find matching documents grows in a straight line with the collection size.
[X] Wrong: "Using $eq always finds results instantly no matter the collection size."
[OK] Correct: Without an index, MongoDB must check each document one by one, so bigger collections take more time.
Understanding how simple equality checks scale helps you explain database query performance clearly and confidently.
"What if we added an index on the age field? How would the time complexity change?"