MongoDB $size Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $size?

$size works with arrays. In aggregation it returns how many elements an array has. In queries it matches documents whose array field has an exact length.

Remember
$size = array length

Aggregation (compute):
  { $size: "$colors" }
  ["blue","black","red"] → 3
  [] → 0

Query (exact match):
  { colors: { $size: 3 } }
  // only arrays with exactly 3 elements

non-array / missing (agg) → error
guard with $isArray when unsure
UsePrefer
Return the countAggregation $size
Exact length filterQuery $size
Length ranges (≥ / ≤)$expr + $size

How to Use $size in MongoDB

Pick compute mode or exact-match filter mode.

  1. To compute length: use $project / $addFields with { $size: "$field" }.
  2. To filter by exact length: use find() or $match with { field: { $size: n } }.
  3. Guard aggregation with $isArray when the field may be missing or a string.
  4. For ranges (e.g. length ≥ 3), use $expr with $gte / $size.
ContextFormResult
Aggregation{ $size: <array> }Returns a number
Query / $match{ field: { $size: n } }Keeps exact length n

Pseudocode

Pseudocode
// Aggregation — compute
for each document:
    arr = evaluate(expression)
    if arr is not an array:
        error
    else:
        result = length(arr)
    emit { ..., field: result }

// Query — filter
keep document if field is an array AND length(field) == n

Cheat Sheet

Keep these facts handy while counting array elements.

TopicDetail
Agg syntax{ $size: <arrayExpression> }
Query syntax{ field: { $size: <n> } }
Empty arrayLength 0
Query rangesNot supported—use $expr
Agg non-arrayErrors—use $isArray
IndexesQuery $size cannot use indexes
Sample["a","b","c"] → 3

Live Preview

Watch aggregation $size count elements in a colors array.

Simulates { $size: "$colors" } (same idea as the mongosh examples below).

Result
colors = ["blue", "black", "red"]
$size → 3

{ numberOfColors: 3 }

Worked Walkthrough — Count Colors

An item has colors: ["blue", "black", "red"]. How many colors is that?

Calculation
Document:
  { item: "ABC1", colors: ["blue", "black", "red"] }

$count the elements:
  1. "blue"
  2. "black"
  3. "red"

$size("$colors") → 3

Empty array [] → 0
Missing / string → aggregation error (guard with $isArray)

MongoDB Examples

We use a small inventory collection. First we compute array lengths safely, then filter by exact size. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine five products. Most have a colors array; one is missing the field; one stores a string by mistake.

mongosh
db.inventory.insertMany([
  { _id: 1, item: "ABC1", colors: ["blue", "black", "red"] },
  { _id: 2, item: "ABC2", colors: ["purple"] },
  { _id: 3, item: "XYZ1", colors: [] },
  { _id: 4, item: "ZZZ1" },
  { _id: 5, item: "ZZZ2", colors: "blue,red" }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps five documents. Run find() to see them:

mongosh
db.inventory.find()

Read one document like this:

Field in MongoDBValue (doc 1)Plain English
item"ABC1"Product code
colors["blue","black","red"]Array of color names

How It Works

  1. Insert once. Five documents land in inventory.
  2. Mixed shapes. Arrays, empty array, missing field, and a string—useful for safe $size.
  3. find() shows the same shape. Ready for counting next.

Example 2 — Count with $size

Goal: return the number of colors, or "NA" when colors is not an array.

mongosh
db.inventory.aggregate([
  {
    $project: {
      item: 1,
      numberOfColors: {
        $cond: {
          if: { $isArray: "$colors" },
          then: { $size: "$colors" },
          else: "NA"
        }
      }
    }
  }
]);

How It Works

  1. Check the type. $isArray is true only for real arrays.
  2. Count safely. When true, $size returns 3, 1, or 0.
  3. Else branch. Missing field and string field return "NA" instead of erroring.
  4. $cond chooses the path. This is the official safe pattern for mixed data.

Example 3 — Exact Length Filter

Goal: keep only documents whose colors array has exactly 3 elements.

mongosh
db.inventory.find({
  colors: { $size: 3 }
});

// same idea in aggregation:
// db.inventory.aggregate([
//   { $match: { colors: { $size: 3 } } }
// ]);

How It Works

  1. Exact match only. Query $size: 3 means length must be exactly 3.
  2. Only ABC1 matches. It has three colors.
  3. Others drop. Length 1, 0, missing, and string fields do not match.
  4. No ranges here. For “3 or more”, use $expr with aggregation $size.

Edge Cases & Pitfalls

Check these before using $size in production pipelines.

type

Aggregation needs a real array

Missing fields or strings make $size error. Guard with $isArray + $cond.

exact

Query $size is exact only

You cannot write “size > 2” with query $size. Use $expr for comparisons.

index

$size cannot use indexes

The $size part of a query does not use indexes. For hot length filters, store a counter field you maintain on write.

empty

Empty array is length 0

[] is still an array. Aggregation returns 0; query { field: { $size: 0 } } matches it.

Performance Notes

ApproachCostBest for
Agg $sizePer-document countReports / derived fields
Query $sizeNo index on sizeExact-length filters
Stored counter fieldIndexableFrequent length queries

Counting short arrays is cheap. If you filter by length often, maintain an integer field (for example colorCount) and index that instead of relying on query $size.

Key Takeaways

  • Agg: $size returns array length.
  • Query: exact length only.
  • Guard non-arrays with $isArray.
  • Ranges: use $expr + $size.

One line: $size answers “how many elements?”—or “keep arrays of this exact length.”

Frequently Asked Questions

$size counts array elements. In aggregation it returns the length: { $size: "$colors" }. In find() / $match queries it matches documents whose array has an exact length: { colors: { $size: 3 } }.
Aggregation: { $size: <arrayExpression> }. Query: { <arrayField>: { $size: <non-negative integer> } }. Query $size only supports an exact count, not a range.
Not with query $size alone—it is exact-match only. In aggregation use $expr with $gte / $gt, for example { $expr: { $gte: [ { $size: "$tags" }, 3 ] } }.
Aggregation $size returns 0 for []. Query { field: { $size: 0 } } matches empty arrays.
It errors. Guard with $isArray (and optionally $cond) when the field may be missing or the wrong type.
The $size portion of a query cannot use indexes. Other parts of the same query still can.

Next: $slice

Return a portion of an array in queries or aggregation.

$slice tutorial →

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.

9 people found this page helpful