$size
The $size operator returns the number of elements in an array.
📌 Syntax
{ "$size": <arrayExpression> }
The input must resolve to an array.
✅ Base Example – Count Elements
📥 Input Document
{ "tags": ["sale", "new", "exclusive"] }
📌 Expression
{ "$size": "$tags" }
📤 Output
3
✅ Base Example – Empty Array
📥 Input Document
{ "items": [] }
📌 Expression
{ "$size": "$items" }
📤 Output
0
🧱 Ecommerce Example – Count Item Features
📌 Pipeline
[
{ "$unwind": "$items" },
{
"$project": {
"product": "$items.name",
"featureCount": { "$size": "$items.features" }
}
}
]
📥 Input Document
{
"items": [
{
"name": "Backpack",
"features": ["Padded", "Waterproof", "Adjustable Straps"]
},
{
"name": "Watch",
"features": []
}
]
}
📤 Output
[
{ "product": "Backpack", "featureCount": 3 },
{ "product": "Watch", "featureCount": 0 }
]
🔧 Common Use Cases
- Count number of tags, features, options
- Validate minimum/maximum items
- Use with
$condor$switchfor conditional logic
🔗 Related Operators
$isArray,$map,$filter,$arrayElemAt
🧠Notes
- Returns an error if input is not an array
- Use
$ifNullor$condfor safety