BSON object size of document retrieved from DB

别等时光非礼了梦想. 提交于 2019-12-10 16:06:45

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/38476377/bson-object-size-of-document-retrieved-from-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!