Get the real document BSON size in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use Object.bsonsize() to get real document size. It prints the BSON size of a document in bytes. Let us create a collection with documents −

> db.demo477.insertOne({"ClientId":1,"ClientName":"Chris"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e82015fb0f3fa88e227908f")
}
> db.demo477.insertOne({"ClientId":2,"ClientName":"David"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e820167b0f3fa88e2279090")
}
> db.demo477.insertOne({"ClientId":3,"ClientName":"Bob"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e82016db0f3fa88e2279091")
}

Display all documents from a collection with the help of find() method −

> db.demo477.find();

This will produce the following output −

{ "_id" : ObjectId("5e82015fb0f3fa88e227908f"), "ClientId" : 1, "ClientName" : "Chris" }
{ "_id" : ObjectId("5e820167b0f3fa88e2279090"), "ClientId" : 2, "ClientName" : "David" }
{ "_id" : ObjectId("5e82016db0f3fa88e2279091"), "ClientId" : 3, "ClientName" : "Bob" }

Following is the query to get the BSON size of a document in bytes −

> Object.bsonsize(db.demo477.findOne())

This will produce the following output −

62
raja
Published on 11-May-2020 13:17:01
Advertisements