0
0
MongoDBquery~5 mins

$count accumulator in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: $count accumulator
O(n)
Understanding Time Complexity

When using the $count accumulator in MongoDB, we want to understand how the time it takes grows as the data size grows.

We ask: How does counting documents scale when the collection gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

db.orders.aggregate([
  { $match: { status: "completed" } },
  { $count: "totalCount" }
])

This code filters orders with status "completed" and then counts how many such orders exist.

Identify Repeating Operations
  • Primary operation: Scanning each document to check if it matches the filter.
  • How many times: Once for each document in the collection or matching subset.
How Execution Grows With Input

As the number of documents grows, the time to check each document and count matching ones grows roughly the same way.

Input Size (n)Approx. Operations
10About 10 checks
100About 100 checks
1000About 1000 checks

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

Final Time Complexity

Time Complexity: O(n)

This means the time to count grows in a straight line with the number of documents.

Common Mistake

[X] Wrong: "Counting documents with $count is instant no matter how many documents there are."

[OK] Correct: MongoDB must look at each document to see if it matches before counting, so more documents mean more work.

Interview Connect

Understanding how counting scales helps you explain database performance clearly and shows you know how data size affects queries.

Self-Check

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