File size: 1,312 Bytes
47ff6b2 e51f7f4 47ff6b2 e51f7f4 47ff6b2 b54297c 47ff6b2 | 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 40 | from motor.motor_asyncio import AsyncIOMotorClient
from app.core.config import settings
class Database:
client: AsyncIOMotorClient = None
def connect_db(self):
# Adding connection pooling for faster concurrent requests
self.client = AsyncIOMotorClient(
settings.MONGODB_URL,
minPoolSize=5,
maxPoolSize=50,
serverSelectionTimeoutMS=5000
)
print("✅ Connected to MongoDB with PoolSize=5-50")
# Ensure proper indexing for student lookups (In background)
import asyncio
asyncio.create_task(self.ensure_indexes())
async def ensure_indexes(self):
try:
collection = self.get_collection()
await collection.create_index([("studentId", 1), ("ownerAdmin", 1)], unique=True)
print("✅ MongoDB Indexes ensured for performance")
except Exception as e:
print(f"⚠️ Index creation warning: {e}")
def close_db(self):
if self.client:
self.client.close()
print("🔌 Disconnected from MongoDB")
def get_collection(self):
if self.client is None:
self.connect_db() # Self-healing on access
return self.client[settings.DB_NAME][settings.COLLECTION_NAME]
db = Database()
|