$size (Get Array Length)
Last updated: 2026-10-09
$size (Get Array Length)
$size returns the number of elements in an array as a non-negative integer. It is the most common array metadata operator, used to count order items, detect empty arrays, or filter documents by array length inside $match via $expr. The argument must be an array; passing a string or number throws an error, and string length should use $strLenCP. $size cannot be used in regular query syntax inside $match — it must go through $expr.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $size: <array> }
⚙️ Parameters
| array | The array expression whose length is computed. |
|---|
Returns:The element count as a non-negative integer; throws when the argument is not an array
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $size: count items per order
db.orders.aggregate([
{ $project: {
itemCount: { $size: '$items' }
} }
])
Output:
{ '_id': 1, 'itemCount': 2 }
{ '_id': 2, 'itemCount': 5 }
📌 Notes
- The argument must be an array or it throws; guard missing fields with $ifNull to an empty array
- Filter array length in $match with { $expr: { $gte: [{ $size: '$tags' }, 3] } }
- Measure string length with $strLenCP, not $size
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QCan $size be used in query conditions?
ANot in plain query syntax — wrap it in $expr, e.g. { $expr: { $gt: [{ $size: '$tags' }, 2] } }.
QWhat happens when the field is missing?
AIt throws. Check with $ifNull or $cond and treat missing as 0.
QCan $size count string length?
ANo, strings are not arrays. Use $strLenCP for string length.