$size (Array Length)
Last updated: 2026-10-09
$size (Array Length)
$size matches documents where an array field has exactly the given length. `{ tags: { $size: 3 } }` matches documents with exactly 3 tags. In queries $size accepts only an exact value — you cannot write { $size: { $gt: 3 } }; for range conditions use $expr with the aggregation $size instead.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ <field>: { $size: <length> } }
⚙️ Parameters
| field | The array field to match. |
|---|---|
| length | The exact number of array elements. |
Returns:Cursor of matching documents
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $size: articles with exactly 3 tags
db.articles.find({ tags: { $size: 3 } })
// At least 3 tags (requires $expr)
db.articles.find({ $expr: { $gte: [{ $size: '$tags' }, 3] } })
Output:
// Returns articles with exactly 3 tags; the second query returns at least 3
📌 Notes
- Queries support exact equality only, not ranges
- For ranges use $expr with { $size: '$tags' } and a comparison operator
- $size does not match documents missing the field
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QCan $size query length greater than a value?
ANot directly. Use $expr: { $gt: [{ $size: '$tags' }, 3] }.
QDoes $size match documents missing the field?
ANo, the field must exist and be an array.
QCan $size: 0 match empty arrays?
AYes, { tags: { $size: 0 } } matches empty arrays; missing fields still do not match.