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 in queries to match documents where an array field has an exact number of elements. You use it inside a query filter like { arrayField: { $size: number } } to find documents with arrays of that specific length.
📐

Syntax

The $size operator is used in a query filter to match documents where the specified array field has exactly the given number of elements.

Syntax parts:

  • arrayField: The name of the array field in the document.
  • $size: The operator that checks the array length.
  • number: The exact number of elements the array must have.
json
{
  arrayField: { $size: number }
}
💻

Example

This example shows how to find documents where the tags array has exactly 3 elements.

javascript
db.articles.insertMany([
  { title: "Article 1", tags: ["mongodb", "database", "nosql"] },
  { title: "Article 2", tags: ["mongodb"] },
  { title: "Article 3", tags: ["database", "nosql"] }
])

// Query to find documents with tags array size 3
const result = db.articles.find({ tags: { $size: 3 } }).toArray()
printjson(result)
Output
[ { "_id": ObjectId("..."), "title": "Article 1", "tags": ["mongodb", "database", "nosql"] } ]
⚠️

Common Pitfalls

Common mistakes when using $size include:

  • Trying to use $size with comparison operators like $gt or $lt. $size only matches exact sizes.
  • Using $size on fields that are not arrays, which will not match any documents.
  • Confusing $size with $exists or $type which check for presence or type, not length.

Correct way to check for array length greater than a number is to use $expr with $gt and $size inside it.

javascript
// Incorrect: This will not work
// db.collection.find({ tags: { $size: { $gt: 2 } } })

// Correct: Use $expr to compare array length
// db.collection.find({ $expr: { $gt: [ { $size: "$tags" }, 2 ] } })
📊

Quick Reference

OperatorDescriptionExample
$sizeMatches arrays with exact length{ tags: { $size: 3 } }
$expr with $sizeCompare array length with operators{ $expr: { $gt: [ { $size: "$tags" }, 2 ] } }

Key Takeaways

Use $size to match arrays with an exact number of elements in MongoDB queries.
$size cannot be combined directly with comparison operators like $gt or $lt.
To query arrays by length greater or less than a number, use $expr with $size inside.
Ensure the field you use $size on is an array to get correct results.
Use $size inside the query filter as { arrayField: { $size: number } }.