How to iterate over all databases and collections in each db and then print the documents in Pymongo?

Hi

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')
5 Likes

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.

1 Like

It is even easier if you are not using variables for the database and collection name as you can just use the attribute style to access those:

for r in conn.test.foo.find({}):
  print(r)

Yes that will be easier if you know the db & collection name ahead of time (say a parameter being passed to a function).

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.