⊕
⊖
Contents
List Collection Names of MongoDB Database
To list collection names present in a MongoDB database,
- Create a client to the MongoDB instance.
- Using the client, and select a database. It returns a reference to the database.
- Call the function list_collection_names() on the database.
- 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)
CopyOutput
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.