0
0
MongoDBquery~10 mins

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

Choose your learning style9 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.