MongoDB $bsonSize Operator

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

What You’ll Learn

The $bsonSize operator returns how many bytes a document or object occupies when encoded as BSON. Use $$ROOT to measure the entire current document, or pass a subdocument field to audit nested data.

01

BSON Bytes

Full encoded size.

02

Syntax

One object expression.

03

$$ROOT

Measure whole document.

04

MongoDB 4.4+

Aggregation operator.

05

Use Cases

Storage, limits, tuning.

06

vs $binarySize

Document vs one field.

Definition and Usage

In MongoDB’s aggregation framework, the $bsonSize operator calculates the BSON-encoded size of an object in bytes. This includes field names, BSON type markers, and values — not just the raw data payload. A small document with long field names can be larger than you expect.

💡
Beginner Tip

MongoDB enforces a 16 MB maximum document size. Use { $bsonSize: "$$ROOT" } to check how close documents are to that limit before inserts or schema changes.

📝 Syntax

The $bsonSize operator takes one object expression:

mongosh
{ $bsonSize: <object> }

Syntax Rules

  • $bsonSize — returns the BSON-encoded size in bytes.
  • <object> — must resolve to an object (document) or null.
  • Use $$ROOT to reference the entire document in the current pipeline stage.
  • Use a field path like "$metadata" to measure a nested subdocument.
  • If the input is null, the result is null.
  • Available in MongoDB 4.4 and later.

💡 $bsonSize vs $binarySize

Both measure bytes, but at different scopes:

$bsonSize — entire BSON object (field names + types + values)
$binarySize — one string or BinData field content only
Example: a document with { name: "Hi", data: BinData(...) }
$bsonSize: "$$ROOT" → full document bytes
$binarySize: "$data" → binary payload bytes only

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (data size)
Syntax{ $bsonSize: <object> }
Whole document{ $bsonSize: "$$ROOT" }
Output unitBytes (integer)
MongoDB version4.4+
Full doc
{
  $bsonSize: "$$ROOT"
}

Current document size

Subdoc
{
  $bsonSize: "$meta"
}

Nested object size

16 MB limit
16 * 1024 * 1024

Max document bytes

Null input
{
  $bsonSize: null
}

Returns null

Examples Gallery

Measure document sizes, audit subdocuments, find the largest records, and sum total BSON storage across a collection.

📚 Document Size

Use an employees collection and measure each document’s BSON size with $$ROOT.

Sample Input Documents

Suppose you have an employees collection:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "name": "Alice",
    "department": "Engineering",
    "skills": ["MongoDB", "Node.js", "React"]
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "name": "Bob",
    "department": "Sales",
    "metadata": { "region": "US", "quota": 50000, "notes": "Top performer" }
  }
]

Example 1 — Measure the Full Document with $$ROOT

Return the BSON size of each document currently being processed:

mongosh
db.employees.aggregate([
  {
    $project: {
      name: 1,
      objectSize: { $bsonSize: "$$ROOT" }
    }
  }
])

How It Works

$$ROOT refers to the whole document at the current pipeline stage. $bsonSize serializes it as BSON and counts every byte, including _id, field names, and array structure.

📈 Practical Patterns

Measure subdocuments, find outliers, and aggregate total collection size.

Example 2 — Measure a Subdocument Field

Check how much space a nested object consumes without counting the rest of the document:

mongosh
db.employees.aggregate([
  {
    $project: {
      name: 1,
      metadataSize: { $bsonSize: "$metadata" },
      rootSize:     { $bsonSize: "$$ROOT" }
    }
  }
])

// Alice (no metadata) → metadataSize: null
// Bob  (has metadata) → metadataSize: ~65, rootSize: ~168

How It Works

Pass any object field to $bsonSize. If the field is missing or null, the result is null. This is useful for comparing which nested structures grow fastest.

Example 3 — Find the Largest Documents

Add a size field, sort descending, and return the top offenders:

mongosh
db.employees.aggregate([
  {
    $addFields: {
      docSize: { $bsonSize: "$$ROOT" }
    }
  },
  { $sort: { docSize: -1 } },
  { $limit: 5 },
  {
    $project: {
      name: 1,
      docSize: 1
    }
  }
])

How It Works

This pattern helps identify documents approaching the 16 MB limit or bloated schemas. On large collections, add { allowDiskUse: true } when sorting.

Example 4 — Sum Total BSON Size Across a Collection

Calculate combined document size for storage reporting:

mongosh
db.employees.aggregate([
  {
    $group: {
      _id: null,
      totalBytes: { $sum: { $bsonSize: "$$ROOT" } },
      docCount:   { $sum: 1 },
      maxBytes:   { $max: { $bsonSize: "$$ROOT" } },
      avgBytes:   { $avg: { $bsonSize: "$$ROOT" } }
    }
  }
])

How It Works

Use $bsonSize inside $sum, $max, and $avg accumulators in a $group stage. This gives collection-level size statistics in one query.

🚀 Use Cases

  • Storage optimization — find documents or subdocuments that consume the most BSON space.
  • 16 MB limit monitoring — detect documents approaching MongoDB’s maximum document size.
  • Schema comparison — measure BSON size before and after renaming fields or restructuring data.
  • Capacity planning — sum $bsonSize across collections for growth estimates.

🧠 How $bsonSize Works

1

MongoDB reads the object

The pipeline evaluates the expression — typically "$$ROOT" or a subdocument field like "$metadata".

Input
2

$bsonSize encodes as BSON

MongoDB serializes the object into BSON format and counts every byte, including type markers and field names.

Encode
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 for optimization

Sort, filter, sum, or alert on document sizes in later pipeline stages.

Conclusion

The $bsonSize operator is essential for understanding how much space your MongoDB documents actually consume on disk. Combined with $$ROOT, it gives you a precise byte count for storage audits and schema tuning.

For beginners, remember: it measures BSON-encoded objects (not single string fields), use $$ROOT for the full document, and pair it with $sort to find outliers.

💡 Best Practices

✅ Do

  • Use $$ROOT to measure the full document size
  • Monitor documents approaching the 16 MB BSON limit
  • Compare subdocument sizes to find bloated nested fields
  • Use allowDiskUse: true when sorting large collections by size
  • Pair with $binarySize when you need field-level detail

❌ Don’t

  • Confuse $bsonSize with $binarySize
  • Expect character count — BSON size includes metadata overhead
  • Use on MongoDB versions before 4.4
  • Pass strings or numbers directly (object or null only)
  • Forget that short field names reduce BSON overhead

Key Takeaways

Knowledge Unlocked

Five things to remember about $bsonSize

Use these points when measuring document storage in MongoDB.

5
Core concepts
📝 02

Simple Syntax

{ $bsonSize: obj }

Syntax
📏 03

$$ROOT

Whole document reference.

Variable
🛠 04

16 MB Limit

Monitor large docs.

Limit
05

Not $binarySize

Document vs one field.

Important

❓ Frequently Asked Questions

$bsonSize returns the size in bytes of a document or object when encoded as BSON. It includes field names, types, and values — not just raw content.
The syntax is { $bsonSize: <object> }. Use $$ROOT to measure the entire current document, or pass a subdocument field like "$metadata".
$$ROOT is a system variable that refers to the whole document currently being processed in the pipeline. { $bsonSize: "$$ROOT" } measures the full document size.
$bsonSize measures an entire BSON-encoded object (document or subdocument). $binarySize measures only a single string or BinData field's content in bytes.
It helps find large documents, monitor storage, stay under MongoDB's 16 MB document limit, and compare schema designs before and after changes.

Continue the Operator Series

Move on to $ceil for rounding up numbers, or review $binarySize for field-level byte counts.

Next: $ceil →

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