convert pymongo cursor to json

I've seen quite a few posts on this issue but they didn't resolve the issue for me. What worked for me was using dumps(), then loads():

import pymongo
from bson.json_util import dumps
from bson.json_util import loads

connection = pymongo.Connection("localhost", 27017)
db = connection.mydocs

def get():
    cursor = db.foo.find({"name" : "bar"})
    return loads(dumps(cursor))

It looks like you want to import from bson not pymongo. I believe json_util was moved to that module recently. https://pymongo.readthedocs.io/en/stable/api/bson/json_util.html


you can use list() to convert pymongo cursor to json object.

import pymongo
from bson.json_util import dumps
from bson.json_util import loads

connection = pymongo.Connection("localhost", 27017)
db = connection.mydocs

def get():
   cursor = list(db.foo.find({"name" : "bar"}))
   return loads(dumps(cursor))

Tags:

Pymongo