rag-chatbot / app /db /mongodb.py
Abeshith's picture
RAG Chatbot with LangChain, FastAPI, and service layer architecture
64d7fdf
from motor.motor_asyncio import AsyncIOMotorClient
from app.config import config
from app.utils.logger import logger
class MongoDB:
def __init__(self):
self.client = None
self.db = None
async def connect(self):
if self.client is None:
mongo_url = config["database"]["mongodb"]["url"]
db_name = config["database"]["mongodb"]["db_name"]
self.client = AsyncIOMotorClient(mongo_url)
self.db = self.client[db_name]
await self.client.admin.command('ping')
logger.info(f"MongoDB connected to database: {db_name}")
return self.db
async def disconnect(self):
if self.client:
self.client.close()
logger.info("MongoDB disconnected")
def get_collection(self, collection_name: str = None):
if collection_name is None:
collection_name = config["database"]["mongodb"]["collection"]
if self.db is None:
raise RuntimeError("MongoDB not connected. Call await connect() first.")
return self.db[collection_name]
async def get_db(self):
if self.db is None:
await self.connect()
return self.db
mongodb = MongoDB()