2 Ways to Get a Document’s Size in MongoDB

If you need to return the size of a document in MongoDB, you can use the following:

Below are examples of each approach.

Sample Data

For the following examples, we’ll use a collection called products with the following documents:

{ "_id" : 1, "product" : { "name" : "Shirt - Short Sleeves", "color" : "White" } }
{ "_id" : 2, "product" : { "name" : "Cap", "color" : "Green" } }
{ "_id" : 3, "product" : { "name" : "Travel Pack", "color" : "Light Blue" } }

Notice that each product field contains an embedded document.

We can return the size of the whole document, or just the embedded object.

The $bsonSize Aggregation Pipeline Operator

We can use the $bsonSize operator with the $$ROOT system variable to get the size of the whole document. The $$ROOT variable refers to the document that’s currently being processed by the pipeline.

Example:

db.products.aggregate([
  {
    $project: {
      "rootSize": { $sum: { $bsonSize: "$$ROOT" } }
    }
  }
])

Result:

{ "_id" : 1, "rootSize" : 81 }
{ "_id" : 2, "rootSize" : 63 }
{ "_id" : 3, "rootSize" : 76 }

In this case we get the size of all documents in the collection, but you can always filter it to just one document or some.

To get the size of the embedded documents, we can replace the $$ROOT variable with the field name of the documents.

Example:

db.products.aggregate([
  {
    $project: {
      "documentSize": { $sum: { $bsonSize: "$product" } }
    }
  }
])

Result:

{ "_id" : 1, "documentSize" : 54 }
{ "_id" : 2, "documentSize" : 36 }
{ "_id" : 3, "documentSize" : 49 }

In this case, the field name is product and so we use $product to refer to that field.

See MongoDB $bsonSize for more information and examples.

The Object.bsonSize() Method

The Object.bsonSize() method is another way to get the size of a document.

Example:

Object.bsonsize(
    db.products.findOne()
)

Result:

81

This method returns just the size and no more.

Note that I used the findOne() method instead of the find() method. I did this because find() only returns a cursor, whereas findOne() returns the actual document.

We can get the size of the embedded document by appending it using dot notation:

Object.bsonsize(
    db.products.findOne().product
)

Result:

54

We can get the size of the next document by specifying its _id as the query argument:

Object.bsonsize(
    db.products.findOne({_id:2}).product
)

Result:

36

See MongoDB Object.bsonSize() for more information and examples.