File size: 1,146 Bytes
8fb6e2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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()