MongoDB $binarySize Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Data Size

What You’ll Learn

The $binarySize operator returns the byte size of a string or BinData value in MongoDB aggregation pipelines. Use it to audit attachments, track storage, or find the largest binary fields.

01

Byte Size

Measure content in bytes.

02

Syntax

One expression inside $binarySize.

03

Strings & BinData

Works on both types.

04

MongoDB 4.4+

Aggregation expression operator.

05

Use Cases

Files, storage, auditing.

06

vs $bsonSize

Field vs whole document.

Definition and Usage

In MongoDB’s aggregation framework, the $binarySize operator returns how many bytes a string or BinData value occupies. For example, the string "Hello" is 5 bytes, and BinData(0, "SGVsbG8=") (base64 for "Hello") is also 5 bytes.

💡
Beginner Tip

$binarySize measures one field’s content. To measure an entire document’s BSON footprint, use $bsonSize instead. They answer different questions.

📝 Syntax

The $binarySize operator takes one expression:

mongosh
{ $binarySize: <expression> }

Syntax Rules

  • $binarySize — returns the size in bytes of the expression value.
  • <expression> — must resolve to a string, BinData, or null.
  • Use it inside stages like $project, $addFields, or $set.
  • If the input is null, the result is null.
  • Arrays, numbers, and other BSON types cause an aggregation error.
  • Available in MongoDB 4.4 and later.

⚠️ Supported Input Types

$binarySize only accepts string and BinData values:

$binarySize: "$fileData"bytes (BinData field)
$binarySize: "$title"bytes (string field)
$binarySize: "$tags"error (array not supported)
$binarySize: nullnull (safe)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (data size)
Syntax{ $binarySize: <expression> }
Accepted typesstring, BinData, null
Output unitBytes (integer)
MongoDB version4.4+
BinData
{
  $binarySize: "$data"
}

File attachment bytes

String
{
  $binarySize: "$title"
}

Text field byte length

Literal
{
  $binarySize: "Hello"
}

Returns 5

Null input
{
  $binarySize: null
}

Returns null

Examples Gallery

Measure binary and string field sizes, find the largest attachment, and sum total bytes across a collection.

📚 Measure Field Size

Use an images collection with BinData file fields and compute byte sizes with $project.

Sample Input Documents

Suppose you have an images collection storing uploaded files as BinData:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "name": "logo.png",
    "binary": BinData(0, "iVBORw0KGgo=")
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "name": "avatar.jpg",
    "binary": BinData(0, "/9j/4AAQSkZJRg==")
  }
]

Example 1 — Basic $binarySize on a BinData Field

Return the byte size of each file’s binary data:

mongosh
db.images.aggregate([
  {
    $project: {
      name: 1,
      imageSize: { $binarySize: "$binary" }
    }
  }
])

How It Works

$binarySize decodes the BinData content and counts its raw bytes. The subtype metadata is not included in the count — only the binary payload size.

📈 Practical Patterns

Measure string fields, find the largest file, and aggregate total storage.

Example 2 — $binarySize on a String Field

Strings are also supported. Measure the byte length of text content:

mongosh
db.posts.aggregate([
  {
    $project: {
      title: 1,
      titleSize: { $binarySize: "$title" },
      bodySize:  { $binarySize: "$body" }
    }
  }
])

// title: "Hello"  → titleSize: 5
// body:  "MongoDB" → bodySize: 7

How It Works

For UTF-8 strings, multi-byte characters count as multiple bytes. This is useful when estimating storage or validating field length limits.

Example 3 — Find the Largest Binary File

Project sizes, sort descending, and return the top result:

mongosh
db.images.aggregate([
  {
    $project: {
      name: 1,
      imageSize: { $binarySize: "$binary" }
    }
  },
  { $sort: { imageSize: -1 } },
  { $limit: 1 }
])

How It Works

Combine $binarySize with $sort and $limit to quickly identify the heaviest binary field in a collection.

Example 4 — Sum Total Binary Storage

Calculate total bytes stored across all documents:

mongosh
db.images.aggregate([
  {
    $project: {
      imageSize: { $binarySize: "$binary" }
    }
  },
  {
    $group: {
      _id: null,
      totalBytes: { $sum: "$imageSize" },
      fileCount:  { $sum: 1 },
      avgBytes:   { $avg: "$imageSize" }
    }
  }
])

How It Works

Project the byte size per document, then use $group with $sum and $avg for collection-level storage statistics. Documents with a null binary field contribute 0 to the sum.

🚀 Use Cases

  • Storage auditing — measure how much space binary attachments consume in a collection.
  • File upload tracking — record and report byte sizes of uploaded images, PDFs, or encoded payloads.
  • Capacity planning — sum binary sizes to estimate growth and set storage alerts.
  • Data quality checks — flag documents with unexpectedly large or empty binary fields.

🧠 How $binarySize Works

1

MongoDB reads the field value

The pipeline evaluates the expression — typically a field like "$binary" or "$title".

Input
2

$binarySize counts the bytes

MongoDB measures the raw content length of the string or BinData value. Unsupported types trigger an error.

Measure
3

The byte count is stored in the pipeline

The integer result is written to the field you define in $project or $addFields.

Output
=

Size data ready for analysis

Sort, filter, sum, or average the byte counts in later pipeline stages.

Conclusion

The $binarySize operator is a practical tool for measuring string and BinData field sizes in MongoDB aggregation pipelines. It answers a simple question: how many bytes does this field contain?

For beginners, remember: it works on strings and BinData only, returns bytes as an integer, and is different from $bsonSize which measures entire documents.

💡 Best Practices

✅ Do

  • Use $binarySize for individual string or BinData fields
  • Combine with $sort to find the largest attachments
  • Use $sum in $group for total storage reports
  • Handle null fields gracefully (they return null, not an error)
  • Use $bsonSize when you need whole-document size

❌ Don’t

  • Pass arrays, numbers, or objects to $binarySize
  • Confuse $binarySize with $bsonSize
  • Assume the count includes BSON type metadata overhead
  • Use on MongoDB versions before 4.4
  • Expect character count for strings — it returns byte length

Key Takeaways

Knowledge Unlocked

Five things to remember about $binarySize

Use these points when measuring data sizes in MongoDB.

5
Core concepts
📝 02

Simple Syntax

{ $binarySize: expr }

Syntax
📏 03

String & BinData

Two supported types.

Input
🛠 04

MongoDB 4.4+

Aggregation operator.

Version
05

Not $bsonSize

Field vs document.

Important

❓ Frequently Asked Questions

$binarySize returns the size in bytes of a string or BinData value. It is useful for measuring file attachments, encoded payloads, or text field lengths at the byte level.
The syntax is { $binarySize: <expression> }. The expression must resolve to a string, BinData, or null.
Yes. $binarySize accepts both strings and BinData values. For strings, it returns the byte length of the string content.
$binarySize measures one string or BinData field in bytes. $bsonSize measures the total BSON-encoded size of an entire document or object.
If the input is null, $binarySize returns null. If the input is an array, number, or other unsupported BSON type, the aggregation returns an error.

Continue the Operator Series

Move on to $bsonSize for whole-document BSON size, or review $arrayElemAt for array access.

Next: $bsonSize →

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