0
0
MongoDBquery~5 mins

$eq for equality in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: $eq for equality
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each document's age field to see if it equals 25.
  • How many times: Once for each document in the collection if no index is used.
How Execution Grows With Input

As the collection grows, the number of documents to check grows too.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The work grows directly with the number of documents.

Final Time Complexity

Time Complexity: O(n)

This means the time to find matching documents grows in a straight line with the collection size.

Common Mistake

[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.

Interview Connect

Understanding how simple equality checks scale helps you explain database query performance clearly and confidently.

Self-Check

"What if we added an index on the age field? How would the time complexity change?"