Bird
Raised Fist0
MongoDBquery~10 mins

Array expressions ($size, $arrayElemAt, $filter) in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Array expressions ($size, $arrayElemAt, $filter)
Start with input array
↓
Apply $size
→Count elements
↓
Apply $arrayElemAt
→Get element at index
↓
Apply $filter
→Check each element with condition
↓
Collect elements passing condition
→Return filtered array
This flow shows how MongoDB array expressions work: $size counts elements, $arrayElemAt picks one element by index, and $filter selects elements matching a condition.
Execution Sample
MongoDB
db.collection.aggregate([
  { $project: {
      totalItems: { $size: "$items" },
      firstItem: { $arrayElemAt: ["$items", 0] },
      filteredItems: { $filter: {
        input: "$items",
        as: "item",
        cond: { $gt: ["$$item.price", 10] }
      }}
  }}
])
This query projects three fields: total count of items, first item, and items with price > 10.
Execution Table
StepExpressionInput ArrayOperationResult
1$size[{price:5},{price:15},{price:20}]Count elements3
2$arrayElemAt[{price:5},{price:15},{price:20}]Get element at index 0{price:5}
3$filter[{price:5},{price:15},{price:20}]Check price > 10 for each element[{price:15},{price:20}]
4End-All expressions evaluatedOutput document with totalItems=3, firstItem={price:5}, filteredItems=[{price:15},{price:20}]
💡 All array expressions processed, results returned in projection.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
items[{price:5},{price:15},{price:20}][{price:5},{price:15},{price:20}][{price:5},{price:15},{price:20}][{price:5},{price:15},{price:20}][{price:5},{price:15},{price:20}]
totalItemsundefined3333
firstItemundefinedundefined{price:5}{price:5}{price:5}
filteredItemsundefinedundefinedundefined[{price:15},{price:20}][{price:15},{price:20}]
Key Moments - 3 Insights
Why does $arrayElemAt with index 0 return the first element, not the last?
Because MongoDB arrays are zero-indexed, so index 0 points to the first element as shown in execution_table row 2.
What happens if $filter condition matches no elements?
The result is an empty array, since $filter collects only elements passing the condition, as seen in execution_table row 3 logic.
Does $size count elements after filtering or before?
$size counts elements in the original array before filtering, as shown in execution_table row 1 counting all items.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of totalItems after step 1?
A3
B2
C0
Dundefined
💡 Hint
Check the 'Result' column in row 1 of execution_table.
At which step does $filter produce its output array?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look for the row where $filter is applied in execution_table.
If the input array was empty, what would $size return?
Anull
Bundefined
C0
Derror
💡 Hint
Recall that $size counts elements; an empty array has zero elements.
Concept Snapshot
$size: counts elements in an array
$arrayElemAt: gets element at given zero-based index
$filter: returns array of elements matching condition
Use in $project to transform documents
All work on arrays, return counts, elements, or filtered arrays
Full Transcript
This visual trace shows how MongoDB array expressions $size, $arrayElemAt, and $filter work step-by-step. Starting with an input array of objects with prices, $size counts how many elements are in the array. $arrayElemAt picks the element at index 0, which is the first element. $filter checks each element's price and returns only those with price greater than 10. The execution table tracks each step's input, operation, and result. Variables like totalItems, firstItem, and filteredItems update as each expression runs. Key moments clarify common confusions like zero-based indexing and filtering behavior. The quiz tests understanding of these steps. This helps beginners see exactly how these array expressions process data in MongoDB aggregation.

Practice

(1/5)
1. What does the MongoDB expression $size do when used on an array field?
easy
A. Counts how many elements are in the array
B. Returns the first element of the array
C. Filters elements based on a condition
D. Sorts the array elements

Solution

  1. Step 1: Understand the purpose of $size

    The $size operator counts the number of elements inside an array.
  2. Step 2: Compare with other operators

    $arrayElemAt picks an element by position, $filter selects elements by condition, and sorting is unrelated.
  3. Final Answer:

    Counts how many elements are in the array -> Option A
  4. Quick Check:

    $size = count elements [OK]
Hint: Remember $size counts array length, not elements themselves [OK]
Common Mistakes:
  • Confusing $size with $arrayElemAt
  • Thinking $size filters elements
  • Assuming $size sorts arrays
2. Which of the following is the correct syntax to get the third element of an array field named items using MongoDB aggregation?
easy
A. { $arrayElemAt: ["items", 3] }
B. { $size: ["$items", 2] }
C. { $arrayElemAt: ["$items", 2] }
D. { $filter: { input: "$items", as: "item", cond: { $eq: ["$$item", 2] } } }

Solution

  1. Step 1: Recall zero-based indexing in $arrayElemAt

    The third element is at index 2 because counting starts at 0.
  2. Step 2: Check syntax correctness

    The correct syntax uses $arrayElemAt with the array field prefixed by $ and the zero-based index.
  3. Final Answer:

    { $arrayElemAt: ["$items", 2] } -> Option C
  4. Quick Check:

    Third element index = 2 [OK]
Hint: Remember arrays start at 0, so third element is index 2 [OK]
Common Mistakes:
  • Using 1-based index instead of 0-based
  • Missing $ before field name
  • Confusing $size with $arrayElemAt
3. Given the document { scores: [10, 20, 30, 40] }, what will the aggregation expression { $size: "$scores" } return?
medium
A. 4
B. 30
C. [10, 20, 30, 40]
D. Error

Solution

  1. Step 1: Understand what $size does

    $size counts the number of elements in the array.
  2. Step 2: Count elements in the array

    The array [10, 20, 30, 40] has 4 elements.
  3. Final Answer:

    4 -> Option A
  4. Quick Check:

    Array length = 4 [OK]
Hint: Count elements inside brackets for $size result [OK]
Common Mistakes:
  • Returning the third element instead of count
  • Returning the whole array instead of count
  • Assuming syntax error
4. Identify the error in this MongoDB aggregation expression: { $arrayElemAt: ["$values", "1"] }
medium
A. Field name missing $ prefix
B. Index must be a number, not a string
C. Array must be inside an object
D. No error, expression is correct

Solution

  1. Step 1: Check the type of index in $arrayElemAt

    The index must be a number, but here it is a string "1".
  2. Step 2: Confirm correct field referencing

    The field name "$values" is correctly prefixed with $.
  3. Final Answer:

    Index must be a number, not a string -> Option B
  4. Quick Check:

    Index type = number, not string [OK]
Hint: Use number type for index in $arrayElemAt [OK]
Common Mistakes:
  • Using string instead of number for index
  • Omitting $ before field name
  • Thinking array must be wrapped differently
5. You have documents with a field tags as an array of strings. How would you write a MongoDB aggregation expression to get the count of tags that start with the letter 'a'?
hard
A. { $size: "$tags" }
B. { $arrayElemAt: ["$tags", 0] }
C. { $filter: { input: "$tags", as: "tag", cond: { $eq: ["$$tag", "a"] } } }
D. { $size: { $filter: { input: "$tags", as: "tag", cond: { $regexMatch: { input: "$$tag", regex: /^a/ } } } } }

Solution

  1. Step 1: Use $filter to select tags starting with 'a'

    The $filter operator creates a new array with tags matching the regex /^a/.
  2. Step 2: Use $size to count filtered tags

    $size counts how many tags matched the condition.
  3. Final Answer:

    { $size: { $filter: { input: "$tags", as: "tag", cond: { $regexMatch: { input: "$$tag", regex: /^a/ } } } } } -> Option D
  4. Quick Check:

    Filter then count = correct approach [OK]
Hint: Filter first, then count with $size for conditional counts [OK]
Common Mistakes:
  • Using $arrayElemAt instead of $filter
  • Filtering with exact match instead of regex
  • Counting whole array without filtering
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard