How do I turn MongoDB query into a JSON?

后端 未结 4 1967
难免孤独
难免孤独 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条回答
  •  走了就别回头了
    2021-01-30 09:46

    Here is a simple sample, using pymongo 2.2.1

    import os
    import sys
    import json
    import pymongo
    from bson import BSON
    from bson import json_util
    
    if __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)
    

提交回复
热议问题