How to Use $size Operator in MongoDB for Array Length Queries
In MongoDB, the
$size operator is used to find documents where an array field has a specific number of elements. You use it inside a query to match arrays of an exact length, like { arrayField: { $size: 3 } } to find arrays with exactly 3 items.Syntax
The $size operator is used in a query to match documents where the specified array field has exactly the given number of elements.
Syntax structure:
{ arrayField: { $size: number } }
Here:
- arrayField is the name of the array field in the document.
- number is the exact length of the array you want to match.
json
{
"arrayField": { "$size": number }
}Example
This example shows how to find documents where the tags array has exactly 2 elements.
javascript
db.products.insertMany([
{ name: "Pen", tags: ["stationery", "writing"] },
{ name: "Notebook", tags: ["stationery"] },
{ name: "Backpack", tags: ["travel", "school", "bag"] }
])
// Query to find products with exactly 2 tags
const result = db.products.find({ tags: { $size: 2 } }).toArray()
printjson(result)Output
[
{
"_id": ObjectId("..."),
"name": "Pen",
"tags": ["stationery", "writing"]
}
]
Common Pitfalls
Common mistakes when using $size include:
- Trying to use
$sizewith comparison operators like$gtor$lt.$sizeonly matches exact array lengths. - Using
$sizeon fields that are not arrays will not match any documents. - Confusing
$sizewith$elemMatchwhich matches array elements by condition, not size.
Correct usage example:
{ tags: { $size: 3 } }Incorrect usage example (won't work):
{ tags: { $size: { $gt: 2 } } }Quick Reference
Summary tips for using $size:
- Use
$sizeto match arrays with an exact number of elements. - It cannot be combined with comparison operators.
- Only works on array fields.
- Use
$elemMatchfor matching array elements by condition.
Key Takeaways
Use
$size to find documents where an array has an exact length.$size does not support greater than or less than comparisons.Ensure the field you query with
$size is an array.For conditional matching inside arrays, use
$elemMatch instead.The syntax is simple:
{ arrayField: { $size: number } }.