Array expressions help you work with lists inside your data. They let you count items, pick specific items, or find items that match a rule.
Array expressions ($size, $arrayElemAt, $filter) in MongoDB
db.collection.aggregate([
{
$project: {
totalItems: { $size: "$arrayField" },
firstItem: { $arrayElemAt: ["$arrayField", 0] },
filteredItems: {
$filter: {
input: "$arrayField",
as: "item",
cond: { /* <condition using $$item> */ }
}
}
}
}
])$size counts how many elements are in an array.
$arrayElemAt gets the element at the given index (starting at 0).
$filter returns a new array with only elements that match the condition.
db.products.aggregate([
{ $project: { numberOfTags: { $size: "$tags" } } }
])db.products.aggregate([
{ $project: { firstTag: { $arrayElemAt: ["$tags", 0] } } }
])db.products.aggregate([
{
$project: {
expensiveTags: {
$filter: {
input: "$tags",
as: "tag",
cond: { $eq: ["$$tag", "expensive"] }
}
}
}
}
])This example inserts three orders with different items and prices. Then it counts how many items each order has, gets the first item, and filters prices greater than 1.
db.orders.insertMany([
{ _id: 1, items: ["apple", "banana", "orange"], prices: [1, 2, 3] },
{ _id: 2, items: ["bread"], prices: [2] },
{ _id: 3, items: [], prices: [] }
])
db.orders.aggregate([
{
$project: {
totalItems: { $size: "$items" },
firstItem: { $arrayElemAt: ["$items", 0] },
expensivePrices: {
$filter: {
input: "$prices",
as: "price",
cond: { $gt: ["$$price", 1] }
}
}
}
}
])$size returns 0 if the array is empty or missing.
$arrayElemAt returns null if the index is out of range.
$filter lets you use variables with $$ to refer to each item.
Counting items is fast, but filtering large arrays can be slower.
$size counts how many elements are in an array.
$arrayElemAt picks one element by its position.
$filter creates a smaller array with only items that match a rule.
Practice
$size do when used on an array field?Solution
Step 1: Understand the purpose of
The$size$sizeoperator counts the number of elements inside an array.Step 2: Compare with other operators
$arrayElemAtpicks an element by position,$filterselects elements by condition, and sorting is unrelated.Final Answer:
Counts how many elements are in the array -> Option AQuick Check:
$size= count elements [OK]
- Confusing $size with $arrayElemAt
- Thinking $size filters elements
- Assuming $size sorts arrays
items using MongoDB aggregation?Solution
Step 1: Recall zero-based indexing in $arrayElemAt
The third element is at index 2 because counting starts at 0.Step 2: Check syntax correctness
The correct syntax uses$arrayElemAtwith the array field prefixed by$and the zero-based index.Final Answer:
{ $arrayElemAt: ["$items", 2] } -> Option CQuick Check:
Third element index = 2 [OK]
- Using 1-based index instead of 0-based
- Missing $ before field name
- Confusing $size with $arrayElemAt
{ scores: [10, 20, 30, 40] }, what will the aggregation expression { $size: "$scores" } return?Solution
Step 1: Understand what
$sizedoes$sizecounts the number of elements in the array.Step 2: Count elements in the array
The array[10, 20, 30, 40]has 4 elements.Final Answer:
4 -> Option AQuick Check:
Array length = 4 [OK]
- Returning the third element instead of count
- Returning the whole array instead of count
- Assuming syntax error
{ $arrayElemAt: ["$values", "1"] }Solution
Step 1: Check the type of index in $arrayElemAt
The index must be a number, but here it is a string "1".Step 2: Confirm correct field referencing
The field name "$values" is correctly prefixed with$.Final Answer:
Index must be a number, not a string -> Option BQuick Check:
Index type = number, not string [OK]
- Using string instead of number for index
- Omitting $ before field name
- Thinking array must be wrapped differently
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'?Solution
Step 1: Use $filter to select tags starting with 'a'
The$filteroperator creates a new array with tags matching the regex /^a/.Step 2: Use $size to count filtered tags
$sizecounts how many tags matched the condition.Final Answer:
{ $size: { $filter: { input: "$tags", as: "tag", cond: { $regexMatch: { input: "$$tag", regex: /^a/ } } } } } -> Option DQuick Check:
Filter then count = correct approach [OK]
- Using $arrayElemAt instead of $filter
- Filtering with exact match instead of regex
- Counting whole array without filtering
Ready to prove it?
Pass the test and this pattern moves unknown
