Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BSON object size of document retrieved from DB

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.

like image 339
fgalan Avatar asked Jul 20 '16 08:07

fgalan


1 Answers

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
like image 137
fgalan Avatar answered Sep 30 '22 10:09

fgalan