MongoDB connector class for FastAPI

i have created Database class . where i i have defined a context manager for db session. and in this context manager i want to handle transaction. like i am doing multiple db transaction and i one transaction is fail then i want no changes in db at all.

am i on right track . or also need to change .

Thanks .

from motor.motor_asyncio import AsyncIOMotorClient
from contextlib import asynccontextmanager
from pymongo.errors import OperationFailure

class Database:
    def __init__(self, db_url: str):
        self.db_url = db_url
        self._client = AsyncIOMotorClient(db_url)

    async def close(self):
        await self._client.close()

    async def session(self):
        async with self._client.start_session() as session:
                async with session.start_transaction():
                    yield session
            except (OperationFailure, Exception) as e:
                print(f"Transaction/session aborted due to exception: {e}")
                await self.close()