0
0
MongodbHow-ToBeginner · 3 min read

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 $size with comparison operators like $gt or $lt. $size only matches exact array lengths.
  • Using $size on fields that are not arrays will not match any documents.
  • Confusing $size with $elemMatch which 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 $size to match arrays with an exact number of elements.
  • It cannot be combined with comparison operators.
  • Only works on array fields.
  • Use $elemMatch for 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 } }.