I am trying to get my hands dirty with PyMongo (latest version) with MongoDB 4.2 (Atlas). I am trying to list out all databases, collections and documents within the collections programmatically. What is the best way to achieve this? I tried the following but something is missing:
for dbname in enumerate(myclient.list_databases()):
print("database name is : ",dbname)
dbc = myclient.dbname;
cols =dbc.list_collection_names()
for coll in cols:
print("collection name is : ", coll)
collection = dbc[coll]
cursor = collection.find({})
for document in cursor:
pprint(document)
Any pointers? Really appreciate it. I can loop through if I hard code the DB name . Things are not working when I want to loop through all DBs and then each collection within a DB and then get to the documents in a collection.
for db_name in conn.list_database_names():
db = conn[db_name]
for coll_name in db.list_collection_names():
print("db: {}, collection:{}".format(db_name, coll_name))
for r in db[coll_name].find({}):
print(r)
print('\n\n')
Wow, that was so slick :). Really appreciate. I think I was trying to complicate it a bit. Didn’t know how to handle the db_name and coll_name properly. I will mark this as a solution.