MongoDB document size can be obtained with Object.bsonsize()

Tadashi Shigeoka ·  Tue, November 20, 2018

For obtaining MongoDB document size, you can calculate it with Object.bsonsize().

MongoDB | モンゴディービー

Calculating document size with Object.bsonsize()

MongoDB document size can be calculated with Object.bsonsize(). The unit is bytes.

> db.test.insert({})
WriteResult({ "nInserted" : 1 })
> db.test.insert({ "a" : 1 })
WriteResult({ "nInserted" : 1 })
> db.test.insert({ "type" : "auto" })
WriteResult({ "nInserted" : 1 })
> db.test.insert({ "type" : "12345" })
WriteResult({ "nInserted" : 1 })

> db.test.find()
{ "_id" : ObjectId("5bf6bdef5ea78d381a18e1a5") }
{ "_id" : ObjectId("5bf6bdef5ea78d381a18e1a6"), "a" : 1 }
{ "_id" : ObjectId("5bf6bd7d5ea78d381a18e1a7"), "type" : "auto" }
{ "_id" : ObjectId("5bf6bdd95ea78d381a18e1a8"), "type" : "12345" }

> Object.bsonsize(db.test.findOne({ "_id" : ObjectId("5bf6bdef5ea78d381a18e1a9") }))
22

> Object.bsonsize(db.test.findOne({ "a" : 1 }))
33

> Object.bsonsize(db.test.findOne({ "type" : "auto" }))
37
> Object.bsonsize(db.test.findOne({ "type" : "12345" }))
38

That’s all from the Gemba where I was suddenly surprised by a MongoDB RangeError.

References