Skip to content

Connection

mongo_ops.connection

Summary

MongoDB connection management.

Classes

MongoConnectionManager

Manages MongoDB connections with async lifecycle.

This class provides a singleton-like manager for the MongoDB client and database instances, ensuring they are properly initialized and closed across the application lifecycle.

Functions
connect async classmethod
1
2
3
connect(
    uri: str, db_name: str, **kwargs: Any
) -> AsyncIOMotorDatabase

Connect to MongoDB and initialize the shared client.

Parameters:

Name Type Description Default
uri str

MongoDB connection URI (e.g., "mongodb://localhost:27017").

required
db_name str

Name of the database to use.

required
**kwargs Any

Additional Motor client options (e.g., maxPoolSize).

{}

Returns:

Name Type Description
AsyncIOMotorDatabase AsyncIOMotorDatabase

The initialized database instance.

disconnect async classmethod
disconnect() -> None

Close the active MongoDB connection and cleanup resources.

get_client classmethod
get_client() -> AsyncIOMotorClient

Retrieve the current client instance.

Returns:

Name Type Description
AsyncIOMotorClient AsyncIOMotorClient

The active Motor client instance.

Raises:

Type Description
RuntimeError

If connect() has not been called yet.

get_database classmethod
get_database() -> AsyncIOMotorDatabase

Retrieve the current database instance.

Returns:

Name Type Description
AsyncIOMotorDatabase AsyncIOMotorDatabase

The active database instance.

Raises:

Type Description
RuntimeError

If connect() has not been called yet.

lifespan async classmethod
1
2
3
lifespan(
    uri: str, db_name: str, **kwargs: Any
) -> AbstractAsyncContextManager[AsyncIOMotorDatabase]

Async context manager for managing connection lifecycle.

Designed for use with FastAPI or other frameworks supporting lifespan management.

Notes

Connects to MongoDB on entry, yields the active database instance to the context body, and disconnects on exit.

Usage

@asynccontextmanager async def lifespan(app: FastAPI): async with MongoConnectionManager.lifespan(uri, db_name): yield