Spaces:
Sleeping
Sleeping
import os | |
from pymongo import MongoClient | |
from dotenv import load_dotenv | |
# Load environment variables | |
load_dotenv() | |
# Initialize MongoDB client | |
atlas_uri = os.getenv("ATLAS_URI") | |
client = MongoClient(atlas_uri) | |
def list_all_collections(): | |
"""List all databases and their collections in the Atlas cluster""" | |
try: | |
# Get all database names | |
db_names = client.list_database_names() | |
print("\nDatabases and Collections in your Atlas cluster:\n") | |
# For each database, get and print collections | |
for db_name in db_names: | |
print(f"Database: {db_name}") | |
db = client[db_name] | |
collections = db.list_collection_names() | |
for collection in collections: | |
# Get count of documents in collection | |
count = db[collection].count_documents({}) | |
print(f" βββ Collection: {collection} ({count} documents)") | |
print() | |
except Exception as e: | |
print(f"Error: {str(e)}") | |
finally: | |
client.close() | |
if __name__ == "__main__": | |
list_all_collections() | |