Introduction to MongoDB $bsonSize Operator

MongoDB is a non-relational database where documents are the basic unit of storage. To handle document size, MongoDB provides operators to compute the size of documents, including the $binarySize and $bsonSize operators. The $bsonSize operator is used to compute the BSON size of a document, which returns the number of bytes in the BSON document. BSON is a binary representation format and is the default storage format for documents in MongoDB. Therefore, using the $bsonSize operator makes it easy to calculate the actual size of MongoDB documents.

Syntax

The syntax of the $bsonSize operator is as follows:

{ $bsonSize: <expression> }

Here, <expression> can be any expression whose return value must be a BSON document.

Use Cases

The $bsonSize operator can be used in the following scenarios:

  • To compute the actual size of a document.
  • For specific documents, comparing their sizes can determine which documents are more suitable for storage in MongoDB.

Examples

Assume we have a collection products that stores product information, where each document has the following format:

{
  "_id": ObjectId("61fb8e9aa20f8355a5e9207a"),
  "name": "iPhone 13",
  "brand": "Apple",
  "price": 999,
  "specs": {
    "screen": "6.1 inches",
    "camera": "12 MP",
    "memory": "128 GB"
  }
}

Now, we want to compute the BSON size of the first document. We can use the following command:

db.products.aggregate([
  {
    $match: { _id: ObjectId("61fb8e9aa20f8355a5e9207a") }
  },
  {
    $project: {
      bsonSize: { $bsonSize: "$$ROOT" }
    }
  }
])

The output of the above command is as follows:

{
  "_id": ObjectId("61fb8e9aa20f8355a5e9207a"),
  "bsonSize": 117
}

Conclusion

The $bsonSize operator is very useful in computing the BSON size of MongoDB documents, and in determining which documents are more suitable for storage in MongoDB. However, it should be noted that the $bsonSize operator does not take into account the size of indexes and other metadata in the collection.