Pretty printing of output in pymongo

2020-03-19 03:22发布

问题:

I am using pymongo driver to work with Mongodb using Python. Every time when I run a query in python shell, it returns me some output which is very difficult to understand. I have used the .pretty() option with mongo shell, which gives the output in a structured way.

I want to know whether there is any method like pretty() in pymongo, which can return output in a structured way ?

回答1:

I want to know whether there is any method like pretty() in PyMongo

No PyMongo doesn't provide such method. It is only available in the shell. You need to use the pprint function from the pprint module.



回答2:

Actually you can also program it by yourself like:

db = connection.[dbname]

collection = db.[yourcollectionname]

for col in collection.find({}):

    for keys in col.keys(): 

        print ('{', keys, ":" , col[keys] , '}' )

I think this will be helpful or take it as an option.



回答3:

No direct method to print out of pymongo in a structured way.

as the out of pymongo is dict

print(json.dumps('variable with out of pymongo query'))

this will serve your purpose i think



回答4:

It probably depends on your IDE, not the pymongo itself. the pymongo is responsible for manipulating data and communicating with the mongodb. I am using Visual Studio with PTVS and I have such options provided from the Visual Studio. The PyCharm is also a good option for IDE that will allow you to watch your code variables and the JSON in a formatted structure.