MongoDB $bsonSize Operator

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

What Is $bsonSize?

$bsonSize is a MongoDB aggregation expression that returns the size in bytes of a document or object when encoded as BSON. It counts field names, type metadata, and values together.

Remember
$bsonSize = BSON-encoded size of an object

{ $bsonSize: <object expression> }

input  → object or null
output → integer bytes (or null)

$$ROOT → whole current document
"$meta" → one subdocument field

null → null
string / array / number → pipeline error
UsePrefer
Whole document or subdocument size$bsonSize
One string or BinData field$binarySize
String byte length only$strLenBytes

How to Use $bsonSize in MongoDB

Pass a document expression (often $$ROOT), then sort or sum the sizes if needed.

  1. Choose an expression stage ($project or $addFields).
  2. Pass "$$ROOT" for the whole document, or a subdocument field like "$meta".
  3. Read the integer byte result from $bsonSize.
  4. Optionally $sort / $limit, or $group with $sum.
PieceRequired?Role
$bsonSizeYesBSON size of an object → bytes
$$ROOT / object fieldYesWhat to measure
$sort / $sumNoFind largest docs or total storage

Pseudocode

Pseudocode
for each document:
    obj = evaluate(expression)   // often $$ROOT
    if obj is null or missing:
        result = null
    else if obj is object:
        result = bson_encode(obj).length   // bytes
    else:
        error  // aggregation fails
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while measuring document sizes.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $bsonSize: <object> }
AcceptedObject (document/subdocument) or null
Whole doc{ $bsonSize: "$$ROOT" }
Subdocument{ $bsonSize: "$meta" }
Limit reminderMongoDB documents max out at 16 MB
Sample check{ _id: 1, name: "Ada" } → 28 bytes

Live Preview

Watch $bsonSize grow as a document gains fields. Each extra key adds name bytes and type metadata, not just the value.

Simulates { $bsonSize: "$$ROOT" } on the sample profiles below.

Result
document = { _id: 2, name: "Grace", city: "NYC" }
$bsonSize($$ROOT) → 44 bytes

{ name: "Grace", objectSize: 44 }

Worked Walkthrough — Why BSON Size Is Bigger Than Text

The string "Ada" is only 3 UTF-8 bytes, but the whole document { _id: 1, name: "Ada" } is 28 bytes in BSON.

Calculation
Document:
  { _id: 1, name: "Ada" }

BSON pays for more than the word "Ada":
  • document length prefix
  • type byte for each field
  • field names: "_id" and "name"
  • value storage (int32 + string length + text + nulls)
  • trailing document null

$bsonSize("$$ROOT") → 28

Compare:
  $binarySize("$name") → 3   (content only)
  $bsonSize("$$ROOT")  → 28  (whole document)

MongoDB Examples

We store three small profiles, measure each document with $$ROOT, then find the largest one. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine a tiny profiles collection. Each document has a little more data than the one before it.

mongosh
db.profiles.insertMany([
  { _id: 1, name: "Ada" },
  { _id: 2, name: "Grace", city: "NYC" },
  { _id: 3, name: "Alan", city: "Cambridge", note: "math" }
]);

How the Data Is Stored in MongoDB

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

mongosh
db.profiles.find()

Read those documents like this:

Field in MongoDBValuePlain English
_id1 … 3Document id for this lesson
name"Ada", "Grace", "Alan"Person name (always present)
city / noteoptional stringsExtra fields that increase BSON size
Picture
Expected BSON sizes (whole document):

  Ada              → 28 bytes
  Grace + city     → 44 bytes
  Alan + city+note → 64 bytes

More fields → more BSON bytes.

How It Works

  1. Insert once. insertMany adds three profile documents to profiles.
  2. Shapes differ on purpose. Ada is smallest; Alan has the most fields.
  3. find() shows the same shape. What you inserted is what you get back—ready for $bsonSize next.

Example 2 — Measure Documents

Goal: project each name with the full document BSON size using $$ROOT.

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

How It Works

  1. Point at the whole document. "$$ROOT" means “the document currently in the pipeline.”
  2. Encode as BSON, count bytes. $bsonSize returns 28, 44, and 64.
  3. Keep a readable label. $project keeps name and adds objectSize.
  4. Subdocuments work the same. Use { $bsonSize: "$meta" } when you only want one nested object.

Example 3 — Find the Largest Document

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

mongosh
db.profiles.aggregate([
  {
    $project: {
      name: 1,
      objectSize: { $bsonSize: "$$ROOT" }
    }
  },
  { $sort: { objectSize: -1 } },
  { $limit: 1 }
]);

How It Works

  1. Measure first. Stage 1 builds objectSize with $bsonSize: "$$ROOT".
  2. Sort biggest first. $sort: { objectSize: -1 } puts 64 ahead of 44 and 28.
  3. Keep one row. $limit: 1 returns only Alan.
  4. Easy check. Alan has the most fields, so 64 bytes is the expected winner.

Edge Cases & Pitfalls

Check these before using $bsonSize in production pipelines.

types

Objects only

Strings, arrays, and numbers make the pipeline fail. Use $binarySize for string/BinData fields, or guard with $type.

null

Null subdocuments return null

Missing or null objects return null, not 0. Handle them before $sum or $sort if nulls are invalid.

overhead

BSON size > content size

Field names and type bytes count. A short string inside a document is always smaller than the whole document’s $bsonSize.

limit

Stay under 16 MB

MongoDB’s document size limit is 16 MB. Use $bsonSize to find docs approaching that ceiling before writes fail.

Performance Notes

ApproachCostBest for
$bsonSize: "$$ROOT"Per-document encode/measureDocument size audits
+ $sort / $limitO(docs) + sortFinding the largest documents
+ $group / $sumO(docs)Total collection BSON footprint

Measuring size is still cheaper than large joins. Filter early with $match when only some documents need a size check.

Key Takeaways

  • Role: BSON size of a document or object → bytes.
  • Whole doc: use "$$ROOT".
  • Inputs: object or null only.
  • Not field content: use $binarySize for one string/BinData field.

One line: $bsonSize answers “how many bytes is this document as BSON?”—including names and metadata, not just the text values.

Frequently Asked Questions

$bsonSize returns the size in bytes of a document or object when encoded as BSON. That includes field names, type bytes, and values—not just the raw string or binary content.
$$ROOT is the whole document currently moving through the pipeline. { $bsonSize: "$$ROOT" } measures that full document’s BSON size.
The argument must resolve to an object (document/subdocument) or null. Strings, arrays, numbers, and other BSON types cause the aggregation to fail with an error.
$bsonSize measures an entire BSON-encoded object. $binarySize measures only one string or BinData field’s content in bytes.
$bsonSize returns null when the input is null or the field is missing. That is useful for optional subdocuments.
It helps find oversized documents, stay aware of MongoDB’s 16 MB document limit, compare schema designs, and sum storage across a collection.

Next: $ceil

Round a number up to the nearest integer in an aggregation pipeline.

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