$size operator for array length in MongoDB - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Counting each element in the
itemsarray to find its length. - How many times: Once per document, and internally once per element in the array.
As the array size grows, the time to count its elements grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to count |
| 100 | About 100 steps to count |
| 1000 | About 1000 steps to count |
Pattern observation: The counting work grows linearly as the array gets bigger.
Time Complexity: O(n)
This means the time to get the array length grows directly with the number of elements in the array.
[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.
Knowing how array operations scale helps you write efficient queries and explain your choices clearly in interviews.
"What if the array was stored as a separate collection and you counted documents instead? How would the time complexity change?"