0

Snippet that fetches records from MongoDB using pymongo client

from bson.json_util import dumps

cursor = db.collections.find({"Test": "Sample"})

for msg in cursor:
    json_msg = dumps(msg)

However, the json_msg is of type string. Is there a way to get JSON object which can be traversed in something like a dict? I want to process the retrieved JSON objects while traversing through them.

I tried json.loads(json_msg) , but that converts the json_msg back to BSON format again.

Edit: I am not looking to just print (which is possible by printing string); however, to iterate and process the JSON object.

KedarX
  • 763
  • 1
  • 7
  • 15

1 Answers1

6

The value returned from collections.find is already a Python dict, which you can iterate. dumps will convert it to a string; so don't dump it, just use it.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895