How do I turn MongoDB query into a JSON? How do I turn MongoDB query into a JSON? mongodb mongodb

How do I turn MongoDB query into a JSON?


The json module won't work due to things like the ObjectID.

Luckily PyMongo provides json_util which ...

... allow[s] for specialized encoding and decoding of BSON documents into Mongo Extended JSON's Strict mode. This lets you encode / decode BSON documents to JSON even when they use special BSON types.


Here is a simple sample, using pymongo 2.2.1

import osimport sysimport jsonimport pymongofrom bson import BSONfrom bson import json_utilif __name__ == '__main__':  try:    connection = pymongo.Connection('mongodb://localhost:27017')    database = connection['mongotest']  except:    print('Error: Unable to Connect')    connection = None  if connection is not None:    database["test"].insert({'name': 'foo'})    doc = database["test"].find_one({'name': 'foo'})    return json.dumps(doc, sort_keys=True, indent=4, default=json_util.default)


It's pretty easy to write a custom serializer which copes with the ObjectIds. Django already includes one which handles decimals and dates, so you can extend that:

from django.core.serializers.json import DjangoJSONEncoderfrom bson import objectidclass MongoAwareEncoder(DjangoJSONEncoder):    """JSON encoder class that adds support for Mongo objectids."""    def default(self, o):        if isinstance(o, objectid.ObjectId):            return str(o)        else:            return super(MongoAwareEncoder, self).default(o)

Now you can just tell json to use your custom serializer:

thejson = json.dumps({'results':posts}, cls=MongoAwareEncoder)