$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.

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $size: <array> }

⚙️ Parameters

arrayThe 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏