$bsonsize

The `$bsonSize` operator is used to return the size of a document in bytes when encoded as BSON. It's useful for understanding the storage requirements of documents within your collections.

Syntax

{ $bsonSize: <expression> }

Parameters

expressionobjectrequired

Any valid expression that resolves to a document whose BSON size you want to calculate

Examples

Calculate the total BSON-encoded size of a document in bytes

This query calculates the BSON size of the document.

Query:

db.stores.aggregate([
  {
    $project: {
      _id: 1,              
      name: 1,         
      documentSize: { 
        $bsonSize: "$$ROOT"
      }
    }
  },
  { $limit: 3 }  
])

Output:

[
  { "_id": "a715ab0f-4c6e-4e9d-a812-f2fab11ce0b6", "name": "Lakeshore Retail | Holiday Supply Hub - Marvinfort", "documentSize": 2226 },
  { "_id": "923d2228-6a28-4856-ac9d-77c39eaf1800", "name": "Lakeshore Retail | Home Decor Hub - Franciscoton", "documentSize": 1365 },
  { "_id": "7e53ca0f-6e24-4177-966c-fe62a11e9af5", "name": "Contoso, Ltd. | Office Supply Deals - South Shana", "documentSize": 1882 }
]

Related