0
0
MongoDBquery~5 mins

$size operator for array length in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: $size operator for array length
O(n)
Understanding Time Complexity

We want to understand how the time it takes to find the length of an array grows as the array gets bigger.

Specifically, how does MongoDB's $size operator behave when counting elements in an array?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


db.collection.aggregate([
  {
    $project: {
      arrayLength: { $size: "$items" }
    }
  }
])
    

This code calculates the length of the items array for each document in the collection.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Counting each element in the items array to find its length.
  • How many times: Once per document, and internally once per element in the array.
How Execution Grows With Input

As the array size grows, the time to count its elements grows roughly in direct proportion.

Input Size (n)Approx. Operations
10About 10 steps to count
100About 100 steps to count
1000About 1000 steps to count

Pattern observation: The counting work grows linearly as the array gets bigger.

Final Time Complexity

Time Complexity: O(n)

This means the time to get the array length grows directly with the number of elements in the array.

Common Mistake

[X] Wrong: "Using $size is instant no matter how big the array is."

[OK] Correct: MongoDB must look at each element to count them, so bigger arrays take more time.

Interview Connect

Knowing how array operations scale helps you write efficient queries and explain your choices clearly in interviews.

Self-Check

"What if the array was stored as a separate collection and you counted documents instead? How would the time complexity change?"