Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get the real document BSON size in MongoDB?
You can use Object.bsonsize() to get the real document BSON size in MongoDB. This method prints the BSON size of a document in bytes, which is useful for understanding storage requirements and optimizing document structure.
Syntax
Object.bsonsize(document)
Sample Data
Let us create a collection with documents ?
db.demo477.insertMany([
{"ClientId": 1, "ClientName": "Chris"},
{"ClientId": 2, "ClientName": "David"},
{"ClientId": 3, "ClientName": "Bob"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e82015fb0f3fa88e227908f"),
ObjectId("5e820167b0f3fa88e2279090"),
ObjectId("5e82016db0f3fa88e2279091")
]
}
Display all documents from the collection ?
db.demo477.find();
{"_id": ObjectId("5e82015fb0f3fa88e227908f"), "ClientId": 1, "ClientName": "Chris"}
{"_id": ObjectId("5e820167b0f3fa88e2279090"), "ClientId": 2, "ClientName": "David"}
{"_id": ObjectId("5e82016db0f3fa88e2279091"), "ClientId": 3, "ClientName": "Bob"}
Example: Get Document BSON Size
Get the BSON size of a document in bytes ?
Object.bsonsize(db.demo477.findOne());
62
Key Points
-
Object.bsonsize()returns the size in bytes of the BSON representation - The size includes all fields, ObjectId, and BSON overhead
- Useful for analyzing storage efficiency and document optimization
Conclusion
Use Object.bsonsize() to measure the actual storage footprint of MongoDB documents. This helps optimize document structure and understand storage requirements for your collections.
Advertisements
