How do I turn MongoDB query into a JSON?

后端 未结 4 2011
难免孤独
难免孤独 2021-01-30 08:54
for p in db.collection.find({\"test_set\":\"abc\"}):
    posts.append(p)
thejson = json.dumps({\'results\':posts})
return  HttpResponse(thejson, mimetype=\"application/j         


        
4条回答
  •  萌比男神i
    2021-01-30 09:39

    Something even simpler which works for me on Python 3.6 using motor==1.1 pymongo==3.4.0

    from bson.json_util import dumps, loads
    
    for mongo_doc in await cursor.to_list(length=10):
        # mongo_doc is a  returned from the async mongo driver, in this acse motor / pymongo.
        # result of executing a simple find() query.
    
        json_string = dumps(mongo_doc)
        # serialize the  into a  
    
        back_to_dict = loads(json_string)
        # to unserialize, thus return the string back to a  with the original 'ObjectID' type.
    

提交回复
热议问题