PyMongo – How to Get Collection Names of MongoDB Database?

List Collection Names of MongoDB Database

To list collection names present in a MongoDB database,

  1. Create a client to the MongoDB instance.
  2. Using the client, and select a database. It returns a reference to the database.
  3. Call the function list_collection_names() on the database.
  4. The functions returns an iterator, use for loop to iterate through the list of collections.

Examples

1. Get list of MongoDB Collections

Following is an example Python program to list the collection names present in a MongoDB Database.

Python Program

import pymongo

myclient = pymongo.MongoClient("mongodb://localhost:27017/")

# Use database "organisation"
mydb = myclient['organisation']

print("List of collections\n--------------------")

# List the collections
for coll in mydb.list_collection_names():
    print(coll)
Copy

Output

PyMongo List Collection Names in Database

Summary

In this PyMongo Tutorial, we learned how to get the list of collections in a MongoDB database using list_collection_names() function, with examples.

Related Tutorials

Code copied to clipboard successfully 👍