Mongo shell have the bsonsize() method to get BSON size of a given document retrieved from DB.
Is there any way of getting the same using PyMongo driver? I have found the bson module in the documentation but it is not fully clear to me how to use it to get the size of a document retrieved from DB.
Based on @SSDMS suggestion (thanks!) the following can be used:
len(bson.BSON.encode(document))
I have tested with a couple of documents in my DB, comparing the result at mongo shell and with the above Python method and getting the same result:
At mongo shell:
> var doc1 = db.entities.findOne({'_id.id': '001'})
> var doc2 = db.entities.findOne({'_id.id': '002'})
> Object.bsonsize(doc1)
816
> Object.bsonsize(doc2)
819
At Python console:
>>> import bson
>>> from pymongo import MongoClient
>>> db = MongoClient('localhost', 27017)
>>> doc1 = db['orion']['entities'].find_one({'_id.id': '001'})
>>> doc2 = db['orion']['entities'].find_one({'_id.id': '002'})
>>> len(bson.BSON.encode(doc1))
816
>>> len(bson.BSON.encode(doc2))
819
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With