Search code examples
apimongoenginebson

How can I convert a MongoEngine Document object to BSON?


The Document class in MongoEngine does not seem to have a "to_bson" function:

from mongoengine import *

class MyDoc(Document):
    foo = StringField()
    bar = IntField()

doc = MyDoc.objects.create(foo=u"Hello World")

print "Document BSON length is:", len(doc.to_bson())  # fails : no "to_bson"

Any solution?


Solution

  • You can use doc.to_mongo() to get dict and pymongo.bson.BSON.from_dict (http://api.mongodb.org/python/1.7/api/pymongo/bson.html to get bson. MongoEngine is wrapper for pymongo.