MongoDB $size Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Array Operations

What You’ll Learn

The $size operator counts elements in an array. Use it in find queries to match an exact array length, or in aggregation pipelines to add a count field and filter by array length dynamically.

01

Count Elements

Array length.

02

Query + Agg

Two contexts.

03

Exact Match

In find queries.

04

$expr Filter

Range counts.

05

Use Cases

Tags, skills, items.

06

Empty = 0

[] returns zero.

Definition and Usage

MongoDB’s $size operator returns how many elements an array contains. In an aggregation pipeline, { $size: "$tags" } produces a number like 3. In a find query, { tags: { $size: 3 } } matches only documents whose tags array has exactly three elements.

This is one of the most practical array operators — use it to validate list lengths, score content by tag count, or find documents with empty arrays.

💡
Beginner Tip

Query $size only supports exact counts. Need “at least 3 tags”? Use aggregation $size inside $match with $expr and $gte.

📝 Syntax

$size has two forms depending on where you use it:

Aggregation Expression

mongosh
{ $size: <array expression> }

Query Operator (Exact Match)

mongosh
{ <arrayField>: { $size: <non-negative integer> } }

Syntax Rules

  • Aggregation — input must resolve to an array; output is a non-negative integer.
  • Query — the integer must be exact; you cannot use $gt or $lt with query $size.
  • Empty array$size of [] is 0.
  • Aggregation: use in $project, $addFields, or $match + $expr.
  • Non-array or null input in aggregation causes an error — guard with $ifNull or $cond + $isArray when needed.

💡 Query $size vs Aggregation $size

Query{ tags: { $size: 2 } } → exactly 2 elements only
Aggregation{ tagCount: { $size: "$tags" } } → adds count field
Range filter$match: { $expr: { $gte: [ { $size: "$tags" }, 3 ] } }
Query form is simpler for exact match; aggregation form is flexible for comparisons

⚡ Quick Reference

QuestionAnswer
Operator typeQuery operator and aggregation expression
Aggregation syntax{ $size: <array> }
Query syntax{ field: { $size: N } }
OutputNon-negative integer (count)
Empty array0
Count field
{
  $size: "$tags"
}

In $project

Exact query
{
  tags: { $size: 3 }
}

Exactly 3 tags

At least N
$expr: {
  $gte: [
    { $size: "$tags" }, 3
  ]
}

3+ tags

Literal
{
  $size: [1, 2, 3]
}

Returns 3

Examples Gallery

Count tags in a projection, find documents with an exact array length, filter by minimum count, and measure set overlap with $size.

📚 Count Array Length

Add a tagCount field to each document using $project.

Sample Input Documents

Suppose you have an articles collection:

mongosh
[
  {
    "_id": 1,
    "title": "Intro to MongoDB",
    "tags": ["mongodb", "database", "tutorial"]
  },
  {
    "_id": 2,
    "title": "Quick Tips",
    "tags": ["mongodb", "tips"]
  },
  {
    "_id": 3,
    "title": "Draft",
    "tags": []
  }
]

Example 1 — Count Tags with $project

Add a numeric field showing how many tags each article has:

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      tags: 1,
      tagCount: { $size: "$tags" }
    }
  }
])

How It Works

$size evaluates the tags array and returns its element count. An empty array returns 0.

📈 Querying and Filtering

Exact-length find queries and flexible range filters in aggregation.

Example 2 — Find Documents With Exactly Two Tags

Use query $size for an exact array length match:

mongosh
db.articles.find({
  tags: { $size: 2 }
})

// Returns "Quick Tips" only

How It Works

Query $size matches only when the array length equals the given integer. It cannot express “2 or more” on its own.

Example 3 — Filter Articles With at Least Three Tags

Use aggregation $size inside $expr for range comparisons:

mongosh
db.articles.aggregate([
  {
    $match: {
      $expr: {
        $gte: [
          { $size: "$tags" },
          3
        ]
      }
    }
  },
  {
    $project: { title: 1, tags: 1 }
  }
])

// Returns "Intro to MongoDB" only

How It Works

$expr lets you use aggregation expressions in $match. Combine $size with $gte, $lte, or $eq for flexible filters.

Example 4 — Count Shared Tags After $setIntersection

Measure overlap size between two tag arrays:

mongosh
db.recommendations.aggregate([
  {
    $project: {
      user: 1,
      overlapCount: {
        $size: {
          $setIntersection: [
            "$userTags",
            "$articleTags"
          ]
        }
      }
    }
  }
])

How It Works

$setIntersection returns the shared elements; $size turns that array into a numeric relevance score. Sort by overlapCount descending for best matches.

🚀 Use Cases

  • Tag and category validation — find articles with exactly or at least N tags.
  • Empty array detection — locate documents with { field: { $size: 0 } }.
  • Relevance scoring — count overlap after set operations like $setIntersection.
  • Data quality checks — flag records where list fields have unexpected lengths.

🧠 How $size Works

1

MongoDB reads the array

In aggregation, the input expression resolves to an array field or literal. In queries, MongoDB checks the named field.

Input
2

Element count is computed

MongoDB counts top-level array elements. Nested arrays count as one element each.

Count
3

Result is used or returned

Aggregation stores the integer in a new field or compares it in $expr. Queries match or exclude documents.

Output
=

Integer count

Use for display, sorting, filtering, or chaining with other operators.

Conclusion

The $size operator counts array elements in both queries and aggregation pipelines. Use the query form for exact-length matches and the aggregation form when you need computed counts or range comparisons.

Pair it with set operators like $setIntersection for overlap scoring, or with $slice to extract portions of arrays after you know their size. Next in the series: $slice.

💡 Best Practices

✅ Do

  • Use query $size for exact array-length filters
  • Use aggregation $size + $expr for “at least N” logic
  • Guard missing fields with $ifNull: [ "$tags", [] ] before $size
  • Combine with $setIntersection for overlap counts
  • Remember empty arrays return 0, not null

❌ Don’t

  • Use query $size with $gt or $lt — it only accepts exact integers
  • Pass non-array values to aggregation $size without checking
  • Confuse element count with byte size (see $bsonSize for document bytes)
  • Expect $size to flatten nested arrays before counting
  • Forget that null input in aggregation causes an error

Key Takeaways

Knowledge Unlocked

Five things to remember about $size

Use these points when counting array elements in MongoDB.

5
Core concepts
📝 02

Query + Agg

Two forms.

Syntax
🛠 03

Exact in find

Integer only.

Query rule
🗃 04

+ $expr

Range filters.

Pattern
05

[] → 0

Empty array.

Edge case

❓ Frequently Asked Questions

$size returns the number of elements in an array. In aggregation pipelines it is an expression: { $size: "$tags" }. In find queries it matches documents where an array field has an exact length: { tags: { $size: 3 } }.
Aggregation syntax: { $size: <array expression> }. Query syntax: { <arrayField>: { $size: <non-negative integer> } }. The query form requires an exact integer match.
Not directly in a find query — query $size only supports exact counts. In aggregation, wrap $size in $expr with $gt or $gte inside $match: { $expr: { $gte: [ { $size: "$tags" }, 3 ] } }.
$size returns 0 for an empty array []. This applies in both aggregation expressions and when matching { field: { $size: 0 } } in queries.
In aggregation, $size on null or a non-array value causes an error. Use $ifNull or $isArray guards when fields may be missing or wrong type.

Continue the Operator Series

Move on to $slice to extract portions of arrays, or review $setIntersection for overlap logic.

Next: $slice →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful