MongoDB $binarySize Operator

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

What Is $binarySize?

$binarySize is a MongoDB aggregation expression that returns the size in bytes of a string or BinData value. For strings it counts UTF-8 bytes (not characters). For BinData it counts the raw binary payload.

Remember
$binarySize = byte length of string or BinData

{ $binarySize: <expression> }

input  → string, BinData, or null
output → integer bytes (or null)

"Hello" → 5
"café"  → 5   (é uses 2 bytes)
""      → 0
null    → null
array / number → pipeline error
UsePrefer
Bytes of one string or BinData field$binarySize
String bytes only (no BinData)$strLenBytes
Whole document BSON footprint$bsonSize

How to Use $binarySize in MongoDB

Pass a string or BinData expression, then sort or filter on the byte count if needed.

  1. Choose an expression stage ($project or $addFields).
  2. Confirm the field is a string or BinData (not an array or number).
  3. Pass that field to $binarySize to get an integer byte count.
  4. Optionally $sort / $limit to find the largest values.
PieceRequired?Role
$binarySizeYesByte length of string or BinData
ExpressionYesField, literal, or nested expression
$sort / $limitNoFind the largest attachment or text

Pseudocode

Pseudocode
for each document:
    v = evaluate(expression)
    if v is null or missing:
        result = null
    else if v is string:
        result = utf8_byte_length(v)
    else if v is BinData:
        result = length(v.payload)   // not the subtype
    else:
        error  // aggregation fails
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while measuring field sizes.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $binarySize: <expression> }
Acceptedstring, BinData, null
OutputInteger bytes (or null)
Empty value"" or empty BinData → 0
UTF-8 tip"café" → 5 bytes (not 4)
VersionMongoDB 4.4+

Live Preview

Watch $binarySize count UTF-8 bytes for a string. Notice that some characters need more than one byte.

Simulates $binarySize on a string (same idea as the mongosh examples below).

Result
text = "café"
characters → 4
$binarySize → 5 bytes

{ text: "café", byteSize: 5 }

Worked Walkthrough — Why café Is 5 Bytes

Four visible characters, five UTF-8 bytes. That difference is why $binarySize matters for storage checks.

Calculation
String: "café"

c  → 1 byte  (ASCII)
a  → 1 byte  (ASCII)
f  → 1 byte  (ASCII)
é  → 2 bytes (UTF-8)

Total = 1 + 1 + 1 + 2 = 5

$binarySize("café") → 5

Compare:
  characters (code points) → 4   ($strLenCP)
  bytes                    → 5   ($binarySize / $strLenBytes)

MongoDB Examples

We store three short messages, measure each title in bytes, then find the longest one. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine a tiny messages collection with three titles. One title uses an accented letter so you can see UTF-8 byte growth.

mongosh
db.messages.insertMany([
  { _id: 1, title: "Hello" },
  { _id: 2, title: "café" },
  { _id: 3, title: "寿司" }
]);

How the Data Is Stored in MongoDB

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

mongosh
db.messages.find()

Read those documents like this:

Field in MongoDBValuePlain English
_id1 … 3Document id for this lesson
title"Hello", "café", "寿司"Text we will measure in bytes
Picture
Expected byte sizes (UTF-8):

  "Hello" → 5 bytes   (all ASCII)
  "café"  → 5 bytes   (é needs 2)
  "寿司"  → 6 bytes   (each char needs 3)

We will ask MongoDB for those numbers with $binarySize.

How It Works

  1. Insert once. insertMany adds three message documents to messages.
  2. MongoDB stores text as UTF-8. The titles look short, but some characters use more than one byte.
  3. find() shows the same shape. What you inserted is what you get back—ready for $binarySize next.

Example 2 — Measure Bytes

Goal: project each title with its byte size using $binarySize.

mongosh
db.messages.aggregate([
  {
    $project: {
      title: 1,
      byteSize: { $binarySize: "$title" }
    }
  }
]);

How It Works

  1. Read each title. The pipeline looks at "$title" for every document from Example 1.
  2. Count UTF-8 bytes. $binarySize returns 5, 5, and 6.
  3. Keep only what you need. $project keeps title and adds byteSize.
  4. Same idea for files. If the field were BinData instead of a string, the syntax stays { $binarySize: "$field" }.

Example 3 — Find the Largest Title

Same collection: measure bytes, sort descending, keep the top row.

mongosh
db.messages.aggregate([
  {
    $project: {
      title: 1,
      byteSize: { $binarySize: "$title" }
    }
  },
  { $sort: { byteSize: -1 } },
  { $limit: 1 }
]);

How It Works

  1. Measure first. Stage 1 builds byteSize with $binarySize (same as Example 2).
  2. Sort biggest first. $sort: { byteSize: -1 } puts 6 ahead of 5.
  3. Keep one row. $limit: 1 returns only "寿司".
  4. Easy check. Two ASCII/Latin titles are 5 bytes; the CJK title is 6—so it wins.

Edge Cases & Pitfalls

Check these before using $binarySize in production pipelines.

types

Only string and BinData

Arrays, numbers, and objects make the pipeline fail. Validate the type or use $cond / $type first.

utf-8

Bytes ≠ characters

Do not treat the result as a character count. For visible length, use $strLenCP.

null

Null and missing become null

Missing fields return null, not 0. Empty strings return 0. Handle both when summing sizes.

scope

Not whole-document size

$binarySize measures one field’s content. For the full BSON document, use $bsonSize.

Performance Notes

ApproachCostBest for
$binarySize alonePer-document scan of field bytesAuditing one string/BinData field
+ $sort / $limitStill O(docs) + sortFinding the heaviest attachments
+ $group / $sumO(docs)Total storage reports

Measuring bytes is cheap compared with large joins. Filter early with $match when only some documents need a size check.

Key Takeaways

  • Role: byte length of a string or BinData value.
  • Inputs: string, BinData, or null only.
  • UTF-8: characters may cost 1–4 bytes each.
  • Scope: one field—use $bsonSize for whole documents.

One line: $binarySize answers “how many bytes is this string or BinData?”—not how many characters, and not how big the whole document is.

Frequently Asked Questions

$binarySize returns the size in bytes of a string or BinData value. Use it inside aggregation expression stages such as $project and $addFields.
The argument must resolve to a string, BinData, or null. Arrays, numbers, objects, and other BSON types cause the aggregation to fail with an error.
For strings, both count UTF-8 bytes. Prefer $binarySize when the field may be BinData or string. Prefer $strLenBytes when you only ever measure strings.
$binarySize measures one string or BinData field’s content. $bsonSize measures the full BSON-encoded size of a document or object, including field names and type metadata.
$binarySize returns null when the input is null or the field is missing. Empty strings and empty BinData return 0, not null.
MongoDB stores strings as UTF-8. ASCII letters use 1 byte each, but characters like é, λ, or emoji may use 2–4 bytes. $binarySize counts bytes, not visible characters.

Next: $bsonSize

Measure the full BSON size of a document or object in an aggregation pipeline.

$bsonSize 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