Return MongoEngine Documents as JSON


Question

Not too sure if this is really simple or not, but I can't really find anything on the topic. But, either using the regular MongoEngine library, or even Flask-MongoEngine for my Flask based website, would it be possible to return a MongoEngine document as straight JSON?

Thanks!

1
9
12/3/2012 4:38:21 PM

Accepted Answer

In 0.8 there are helpers see https://github.com/MongoEngine/mongoengine/issues/1

in the meantime you have to use pymongo's json_utils directly:

from bson import json_util
json_util.dumps(MyDoc._collection_obj.find(MyDoc.objects()._query))
7
12/3/2012 8:43:30 PM

Ross's and Jellyflower's workarounds don't work when field projection or ordering is used.

More general workaround:

from bson import json_util
json = json_util.dumps(query._cursor)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon