{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"mongo_ops","text":""},{"location":"#mongo_ops","title":"mongo_ops","text":""},{"location":"#mongo_ops--summary","title":"Summary","text":"

mongo-ops: A modular MongoDB operations layer for FastAPI microservices.

This package provide a standardized way to interact with MongoDB in async Python applications, particularly optimized for FastAPI. It includes:

Example
from mongo_ops import BaseDocument, BaseRepository, CachedBaseRepository\nfrom mongo_ops.cache import InMemoryCacheBackend, CacheConfig\n\nclass User(BaseDocument):\n    username: str\n\nclass UserRepository(BaseRepository[User]):\n    def __init__(self):\n        super().__init__(\"users\", User)\n\n# With caching:\ncache = InMemoryCacheBackend()\nclass CachedUserRepo(CachedBaseRepository[User]):\n    def __init__(self):\n        super().__init__(\"users\", User, cache)\n
"},{"location":"#mongo_ops-classes","title":"Classes","text":""},{"location":"#mongo_ops.BaseDocument","title":"BaseDocument","text":"

Bases: BaseModel

Base document class with common MongoDB fields.

Inherit from this class to create Pydantic models that represent MongoDB documents. It includes automatic handling of the _id field and timestamps.

Attributes:

Name Type Description id PyObjectId | None

The MongoDB document ID (aliased to _id).

created_at datetime

Timestamp when the document was created.

updated_at datetime

Timestamp when the document was last updated.

"},{"location":"#mongo_ops.BaseRepository","title":"BaseRepository","text":"
BaseRepository(collection_name: str, model: type[T])\n

Bases: CRUDMixin[T], Generic[T]

Base repository class combining CRUD operations and collection management.

This class simplifies repository creation by automatically obtaining the database connection and collection instance.

Attributes:

Name Type Description collection_name str

The name of the collection managed by this repository.

Initialize the repository.

Parameters:

Name Type Description Default collection_name str

The name of the MongoDB collection.

required model type[T]

The Pydantic model class.

required"},{"location":"#mongo_ops.BaseRepository-functions","title":"Functions","text":""},{"location":"#mongo_ops.BaseRepository.count","title":"count async","text":"
count(filter: dict[str, Any] | None = None) -> int\n

Count documents matching a filter.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary.

None

Returns:

Name Type Description int int

The number of matching documents.

"},{"location":"#mongo_ops.BaseRepository.create","title":"create async","text":"
create(data: T) -> T\n

Create a new document in the collection.

Parameters:

Name Type Description Default data T

The Pydantic model instance to insert.

required

Returns:

Name Type Description T T

The created Pydantic model instance, including the assigned ID.

"},{"location":"#mongo_ops.BaseRepository.delete","title":"delete async","text":"
delete(id: str | ObjectId) -> bool\n

Delete a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Name Type Description bool bool

True if a document was deleted, False otherwise.

"},{"location":"#mongo_ops.BaseRepository.get_by_id","title":"get_by_id async","text":"
get_by_id(id: str | ObjectId) -> T | None\n

Retrieve a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Type Description T | None

Optional[T]: The Pydantic model instance if found, else None.

"},{"location":"#mongo_ops.BaseRepository.get_many","title":"get_many async","text":"
get_many(\n    filter: dict[str, Any] | None = None,\n    skip: int = 0,\n    limit: int = 100,\n    sort: list[tuple] | None = None,\n) -> list[T]\n

Retrieve multiple documents with filtering, pagination, and sorting.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary (e.g., {\"is_active\": True}).

None skip int

Number of documents to skip for pagination.

0 limit int

Maximum number of documents to return (default 100).

100 sort Optional[List[tuple]]

List of sort specifications [(field, direction), ...]. E.g., [(\"created_at\", -1)] for descending.

None

Returns:

Type Description list[T]

List[T]: A list of Pydantic model instances.

Example
users = await repo.get_many(\n    filter={\"role\": \"admin\"},\n    limit=10,\n    sort=[(\"username\", 1)]\n)\n
"},{"location":"#mongo_ops.BaseRepository.patch","title":"patch async","text":"
patch(id: str | ObjectId, data: dict[str, Any]) -> T | None\n

Partially update a document using $set (REST PATCH semantics).

Unlike update(), patch() takes a partial dict and applies only those fields. PopulatingRepository overrides this to prevent patching FK fields.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required data Dict[str, Any]

A partial dictionary of fields and values to update.

required

Returns:

Type Description T | None

Optional[T]: The updated Pydantic model instance if found, else None.

"},{"location":"#mongo_ops.BaseRepository.update","title":"update async","text":"
update(\n    id: str | ObjectId, data: dict[str, Any]\n) -> T | None\n

Update a document by its ID using the $set operator.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required data Dict[str, Any]

A dictionary of fields and values to update.

required

Returns:

Type Description T | None

Optional[T]: The updated Pydantic model instance if found, else None.

Example
updated_user = await repo.update(user_id, {\"email\": \"new@example.com\"})\n
"},{"location":"#mongo_ops.CRUDMixin","title":"CRUDMixin","text":"
CRUDMixin(\n    collection: AsyncIOMotorCollection, model: type[T]\n)\n

Bases: Generic[T]

Generic CRUD operations mixin for MongoDB collections.

This mixin provides standard Create, Read, Update, and Delete operations that work with Pydantic models.

Attributes:

Name Type Description collection AsyncIOMotorCollection

The Motor collection instance.

model type[T]

The Pydantic model class representing the document.

Initialize the CRUD mixin.

Parameters:

Name Type Description Default collection AsyncIOMotorCollection

The Motor collection to operate on.

required model type[T]

The Pydantic model class (subclass of BaseDocument).

required"},{"location":"#mongo_ops.CRUDMixin-functions","title":"Functions","text":""},{"location":"#mongo_ops.CRUDMixin.count","title":"count async","text":"
count(filter: dict[str, Any] | None = None) -> int\n

Count documents matching a filter.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary.

None

Returns:

Name Type Description int int

The number of matching documents.

"},{"location":"#mongo_ops.CRUDMixin.create","title":"create async","text":"
create(data: T) -> T\n

Create a new document in the collection.

Parameters:

Name Type Description Default data T

The Pydantic model instance to insert.

required

Returns:

Name Type Description T T

The created Pydantic model instance, including the assigned ID.

"},{"location":"#mongo_ops.CRUDMixin.delete","title":"delete async","text":"
delete(id: str | ObjectId) -> bool\n

Delete a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Name Type Description bool bool

True if a document was deleted, False otherwise.

"},{"location":"#mongo_ops.CRUDMixin.get_by_id","title":"get_by_id async","text":"
get_by_id(id: str | ObjectId) -> T | None\n

Retrieve a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Type Description T | None

Optional[T]: The Pydantic model instance if found, else None.

"},{"location":"#mongo_ops.CRUDMixin.get_many","title":"get_many async","text":"
get_many(\n    filter: dict[str, Any] | None = None,\n    skip: int = 0,\n    limit: int = 100,\n    sort: list[tuple] | None = None,\n) -> list[T]\n

Retrieve multiple documents with filtering, pagination, and sorting.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary (e.g., {\"is_active\": True}).

None skip int

Number of documents to skip for pagination.

0 limit int

Maximum number of documents to return (default 100).

100 sort Optional[List[tuple]]

List of sort specifications [(field, direction), ...]. E.g., [(\"created_at\", -1)] for descending.

None

Returns:

Type Description list[T]

List[T]: A list of Pydantic model instances.

Example
users = await repo.get_many(\n    filter={\"role\": \"admin\"},\n    limit=10,\n    sort=[(\"username\", 1)]\n)\n
"},{"location":"#mongo_ops.CRUDMixin.patch","title":"patch async","text":"
patch(id: str | ObjectId, data: dict[str, Any]) -> T | None\n

Partially update a document using $set (REST PATCH semantics).

Unlike update(), patch() takes a partial dict and applies only those fields. PopulatingRepository overrides this to prevent patching FK fields.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required data Dict[str, Any]

A partial dictionary of fields and values to update.

required

Returns:

Type Description T | None

Optional[T]: The updated Pydantic model instance if found, else None.

"},{"location":"#mongo_ops.CRUDMixin.update","title":"update async","text":"
update(\n    id: str | ObjectId, data: dict[str, Any]\n) -> T | None\n

Update a document by its ID using the $set operator.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required data Dict[str, Any]

A dictionary of fields and values to update.

required

Returns:

Type Description T | None

Optional[T]: The updated Pydantic model instance if found, else None.

Example
updated_user = await repo.update(user_id, {\"email\": \"new@example.com\"})\n
"},{"location":"#mongo_ops.CachedBaseRepository","title":"CachedBaseRepository","text":"
CachedBaseRepository(\n    collection_name: str,\n    model: type[T],\n    cache_backend: CacheBackend,\n    config: CacheConfig | None = None,\n)\n

Bases: BaseRepository[T], Generic[T]

Repository that reads and writes through a cache backend.

Wraps an existing BaseRepository with an ID-keyed cache. Reads consult the backend first and fall through to MongoDB on a miss, populating the cache on success. Writes invalidate or refresh the affected key.

Notes

Guarantees:

- The cache holds the raw document shape (``model_dump``), so FK\n  references round-trip as hex strings, not populated models.\n- When ``config.enabled`` is False the repository behaves exactly\n  like its parent with no cache access.\n

Initialize the cached repository.

Parameters:

Name Type Description Default collection_name str

Name of the MongoDB collection.

required model type[T]

The Pydantic model class.

required cache_backend CacheBackend

Backend used to store and fetch entries.

required config Optional[CacheConfig]

Cache configuration; a default CacheConfig is used when None.

None"},{"location":"#mongo_ops.CachedBaseRepository-functions","title":"Functions","text":""},{"location":"#mongo_ops.CachedBaseRepository.count","title":"count async","text":"
count(filter: dict[str, Any] | None = None) -> int\n

Count documents matching a filter.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary.

None

Returns:

Name Type Description int int

The number of matching documents.

"},{"location":"#mongo_ops.CachedBaseRepository.create","title":"create async","text":"
create(data: T) -> T\n

Insert a document and cache the raw snapshot.

Parameters:

Name Type Description Default data T

The model instance to insert.

required

Returns:

Name Type Description T T

The created model instance, including its ID.

"},{"location":"#mongo_ops.CachedBaseRepository.delete","title":"delete async","text":"
delete(id: str | ObjectId) -> bool\n

Delete a document and remove its cache entry.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID.

required

Returns:

Name Type Description bool bool

True if a document was deleted, False otherwise.

"},{"location":"#mongo_ops.CachedBaseRepository.get_by_id","title":"get_by_id async","text":"
get_by_id(id: str | ObjectId) -> T | None\n

Fetch a document, reading through the cache when enabled.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID.

required

Returns:

Type Description T | None

Optional[T]: The model instance, or None when not found.

"},{"location":"#mongo_ops.CachedBaseRepository.get_many","title":"get_many async","text":"
get_many(\n    filter: dict[str, Any] | None = None,\n    skip: int = 0,\n    limit: int = 100,\n    sort: list[tuple] | None = None,\n) -> list[T]\n

Retrieve multiple documents with filtering, pagination, and sorting.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary (e.g., {\"is_active\": True}).

None skip int

Number of documents to skip for pagination.

0 limit int

Maximum number of documents to return (default 100).

100 sort Optional[List[tuple]]

List of sort specifications [(field, direction), ...]. E.g., [(\"created_at\", -1)] for descending.

None

Returns:

Type Description list[T]

List[T]: A list of Pydantic model instances.

Example
users = await repo.get_many(\n    filter={\"role\": \"admin\"},\n    limit=10,\n    sort=[(\"username\", 1)]\n)\n
"},{"location":"#mongo_ops.CachedBaseRepository.invalidate_cache","title":"invalidate_cache async","text":"
invalidate_cache(id: str | ObjectId) -> None\n

Remove a single document's cache entry.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID to invalidate.

required"},{"location":"#mongo_ops.CachedBaseRepository.patch","title":"patch async","text":"
patch(id: str | ObjectId, data: dict[str, Any]) -> T | None\n

Partially update a document using $set (REST PATCH semantics).

Unlike update(), patch() takes a partial dict and applies only those fields. PopulatingRepository overrides this to prevent patching FK fields.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required data Dict[str, Any]

A partial dictionary of fields and values to update.

required

Returns:

Type Description T | None

Optional[T]: The updated Pydantic model instance if found, else None.

"},{"location":"#mongo_ops.CachedBaseRepository.update","title":"update async","text":"
update(id: str | ObjectId, data: dict) -> T | None\n

Update a document and refresh its cache entry.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID.

required data dict

Fields to set via $set.

required

Returns:

Type Description T | None

Optional[T]: The updated model instance, or None when not found.

"},{"location":"#mongo_ops.CachedBaseRepository.warm_cache","title":"warm_cache async","text":"
warm_cache(ids: list[str | ObjectId]) -> int\n

Pre-populate the cache for a set of document IDs.

Docs already present in the cache are skipped.

Parameters:

Name Type Description Default ids list[Union[str, ObjectId]]

Document IDs to warm.

required

Returns:

Name Type Description int int

Number of entries added to the cache.

"},{"location":"#mongo_ops.ModelRegistry","title":"ModelRegistry","text":"

Registry for managing multiple models and their collections.

This registry allows central management of collections and their associated indexes, making it easier to perform mass initialization at application startup.

"},{"location":"#mongo_ops.ModelRegistry-functions","title":"Functions","text":""},{"location":"#mongo_ops.ModelRegistry.get_cache_backend","title":"get_cache_backend classmethod","text":"
get_cache_backend() -> CacheBackend | None\n

Get the registered cache backend instance.

Returns:

Type Description CacheBackend | None

Optional[CacheBackend]: The cache backend, if registered.

"},{"location":"#mongo_ops.ModelRegistry.get_model","title":"get_model classmethod","text":"
get_model(collection_name: str) -> type[BaseDocument]\n

Retrieve a registered model by its collection name.

Parameters:

Name Type Description Default collection_name str

The name of the collection.

required

Returns:

Type Description type[BaseDocument]

type[BaseDocument]: The registered model class.

Raises:

Type Description KeyError

If the model for the given collection is not registered.

"},{"location":"#mongo_ops.ModelRegistry.initialize_all","title":"initialize_all async classmethod","text":"
initialize_all(\n    db: AsyncIOMotorDatabase | None = None,\n) -> None\n

Initialize all registered collections and create indexes.

This method should be called during application startup to ensure all necessary indexes exist in the database.

Parameters:

Name Type Description Default db Optional[AsyncIOMotorDatabase]

Database instance. If not provided, uses the global database from MongoConnectionManager.

None"},{"location":"#mongo_ops.ModelRegistry.initialize_cache","title":"initialize_cache async classmethod","text":"
initialize_cache() -> None\n

Initialize the registered cache backend.

Must be called after set_cache_backend() and before any cache-backed repository operations. Typically called right after MongoDB connection is established.

Raises:

Type Description RuntimeError

If no cache backend has been registered.

"},{"location":"#mongo_ops.ModelRegistry.list_collections","title":"list_collections classmethod","text":"
list_collections() -> list[str]\n

List all registered collection names.

Returns:

Type Description list[str]

list[str]: A list of collection names.

"},{"location":"#mongo_ops.ModelRegistry.register","title":"register classmethod","text":"
register(\n    collection_name: str,\n    model: type[BaseDocument],\n    indexes: list[tuple] | None = None,\n) -> None\n

Register a model with its collection and indexes.

Parameters:

Name Type Description Default collection_name str

Name of the MongoDB collection.

required model type[BaseDocument]

Document model class (subclass of BaseDocument).

required indexes list[Any]

List of index specifications. Each spec is passed directly to pymongo's create_index. Supported forms: - single field: (\"email\", 1) - compound: [(\"author_id\", 1), (\"created_at\", -1)] - with options: {\"keys\": [(\"username\", 1)], \"options\": {\"unique\": True}}

None Example

ModelRegistry.register(\"users\", UserDocument, indexes=[(\"email\", 1)]) ModelRegistry.register( \"posts\", PostDocument, indexes=[[(\"author_id\", 1), (\"created_at\", -1)]], )

"},{"location":"#mongo_ops.ModelRegistry.set_cache_backend","title":"set_cache_backend classmethod","text":"
set_cache_backend(backend: CacheBackend) -> None\n

Register a cache backend for all cache-enabled repositories.

Should be called after MongoDB connection is established, before cache-backed repositories are used.

Parameters:

Name Type Description Default backend CacheBackend

A CacheBackend instance (InMemoryCacheBackend or RedisCacheBackend).

required"},{"location":"#mongo_ops.ModelRegistry.shutdown_cache","title":"shutdown_cache async classmethod","text":"
shutdown_cache() -> None\n

Shutdown the registered cache backend gracefully.

Should be called during application shutdown to clean up background tasks (e.g., in-memory TTL cleanup).

"},{"location":"#mongo_ops.MongoConnectionManager","title":"MongoConnectionManager","text":"

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.

"},{"location":"#mongo_ops.MongoConnectionManager-functions","title":"Functions","text":""},{"location":"#mongo_ops.MongoConnectionManager.connect","title":"connect async classmethod","text":"
connect(\n    uri: str, db_name: str, **kwargs: Any\n) -> AsyncIOMotorDatabase\n

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.

"},{"location":"#mongo_ops.MongoConnectionManager.disconnect","title":"disconnect async classmethod","text":"
disconnect() -> None\n

Close the active MongoDB connection and cleanup resources.

"},{"location":"#mongo_ops.MongoConnectionManager.get_client","title":"get_client classmethod","text":"
get_client() -> AsyncIOMotorClient\n

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.

"},{"location":"#mongo_ops.MongoConnectionManager.get_database","title":"get_database classmethod","text":"
get_database() -> AsyncIOMotorDatabase\n

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.

"},{"location":"#mongo_ops.MongoConnectionManager.lifespan","title":"lifespan async classmethod","text":"
lifespan(\n    uri: str, db_name: str, **kwargs: Any\n) -> AbstractAsyncContextManager[AsyncIOMotorDatabase]\n

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

"},{"location":"#mongo_ops.PopulatingRepository","title":"PopulatingRepository","text":"
PopulatingRepository(\n    collection_name: str,\n    model: type[T],\n    population_engine: PopulationEngine | None = None,\n    populate_rules: list[PopulateRule] | None = None,\n)\n

Bases: BaseRepository[T], Generic[T]

Repository that auto-populates and depopulates FK references.

On read, ObjectId FK fields are resolved to model instances according to the configured PopulateRules. On write, populated model references are collapsed back to ObjectIds before hitting MongoDB.

Notes

Guarantees:

- Populate rules apply on both read (data_to_model) and write\n  (create/update) paths.\n- Patching FK fields via patch() is rejected.\n- Class attributes `population_engine` and `_populate_rules` must\n  be set (see set_population_engine/set_populate_rules) for any\n  population to occur.\n

Initialize the repository.

Parameters:

Name Type Description Default collection_name str

Name of the MongoDB collection.

required model type[T]

The Pydantic model class.

required population_engine Optional[PopulationEngine]

Engine used to resolve references. Defaults to None.

None populate_rules Optional[list[PopulateRule]]

Rules describing FK resolution. Defaults to None (no rules).

None"},{"location":"#mongo_ops.PopulatingRepository-functions","title":"Functions","text":""},{"location":"#mongo_ops.PopulatingRepository.count","title":"count async","text":"
count(filter: dict[str, Any] | None = None) -> int\n

Count documents matching a filter.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary.

None

Returns:

Name Type Description int int

The number of matching documents.

"},{"location":"#mongo_ops.PopulatingRepository.create","title":"create async","text":"
create(data: T) -> T\n

Depopulate, insert, and re-populate a new document.

Parameters:

Name Type Description Default data T

The model instance to insert (FK fields may hold models).

required

Returns:

Name Type Description T T

The created model instance, including its ID.

"},{"location":"#mongo_ops.PopulatingRepository.data_to_model","title":"data_to_model async","text":"
data_to_model(data: dict) -> T\n

Convert a raw dict to a model, resolving FK references first.

Parameters:

Name Type Description Default data dict

Raw document dictionary.

required

Returns:

Name Type Description T T

The populated model instance.

Raises:

Type Description ValueError

If a FK field holds an embedded dict instead of an ObjectId.

"},{"location":"#mongo_ops.PopulatingRepository.delete","title":"delete async","text":"
delete(id: str | ObjectId) -> bool\n

Delete a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Name Type Description bool bool

True if a document was deleted, False otherwise.

"},{"location":"#mongo_ops.PopulatingRepository.get_by_id","title":"get_by_id async","text":"
get_by_id(id: str | ObjectId) -> T | None\n

Retrieve a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Type Description T | None

Optional[T]: The Pydantic model instance if found, else None.

"},{"location":"#mongo_ops.PopulatingRepository.get_many","title":"get_many async","text":"
get_many(\n    filter: dict[str, Any] | None = None,\n    skip: int = 0,\n    limit: int = 100,\n    sort: list[tuple] | None = None,\n) -> list[T]\n

Retrieve multiple documents with filtering, pagination, and sorting.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary (e.g., {\"is_active\": True}).

None skip int

Number of documents to skip for pagination.

0 limit int

Maximum number of documents to return (default 100).

100 sort Optional[List[tuple]]

List of sort specifications [(field, direction), ...]. E.g., [(\"created_at\", -1)] for descending.

None

Returns:

Type Description list[T]

List[T]: A list of Pydantic model instances.

Example
users = await repo.get_many(\n    filter={\"role\": \"admin\"},\n    limit=10,\n    sort=[(\"username\", 1)]\n)\n
"},{"location":"#mongo_ops.PopulatingRepository.patch","title":"patch async","text":"
patch(id: str | ObjectId, data: dict[str, Any]) -> T | None\n

Partially update a document, rejecting FK field changes.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID.

required data dict[str, Any]

Partial dictionary of fields to update.

required

Returns:

Type Description T | None

Optional[T]: The updated model instance, or None when not found.

Raises:

Type Description ValueError

If any FK field is present in the patch payload.

"},{"location":"#mongo_ops.PopulatingRepository.set_populate_rules","title":"set_populate_rules","text":"
set_populate_rules(rules: list[PopulateRule]) -> None\n

Set the FK resolution rules.

Parameters:

Name Type Description Default rules list[PopulateRule]

Rules describing which fields resolve and how deep.

required"},{"location":"#mongo_ops.PopulatingRepository.set_population_engine","title":"set_population_engine","text":"
set_population_engine(engine: PopulationEngine) -> None\n

Attach (or replace) the population engine.

Parameters:

Name Type Description Default engine PopulationEngine

Engine used to resolve references.

required"},{"location":"#mongo_ops.PopulatingRepository.update","title":"update async","text":"
update(id: str | ObjectId, data: T) -> T | None\n

Depopulate and update a document by ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID.

required data T

The model instance holding the updated fields.

required

Returns:

Type Description T | None

Optional[T]: The updated model instance, or None when not found.

"},{"location":"#mongo_ops.TransactionManager","title":"TransactionManager","text":"

Simplified multi-document transaction handling.

This class provides helpers for executing operations within a MongoDB transaction, ensuring ACID compliance for multi-document updates.

"},{"location":"#mongo_ops.TransactionManager-functions","title":"Functions","text":""},{"location":"#mongo_ops.TransactionManager.execute_transaction","title":"execute_transaction async classmethod","text":"
execute_transaction(\n    operations: list[\n        Callable[\n            [AsyncIOMotorClientSession], Awaitable[Any]\n        ]\n    ],\n    **kwargs: Any\n) -> list[Any]\n

Execute multiple operations within a single transaction.

Parameters:

Name Type Description Default operations List[Callable[[AsyncIOMotorClientSession], Awaitable[Any]]]

A list of async callables that accept a session parameter and return a result.

required **kwargs Any

Transaction options.

{}

Returns:

Type Description list[Any]

List[Any]: A list containing the results of each operation.

Example

results = await TransactionManager.execute_transaction([ lambda s: repo1.create(data1, session=s), lambda s: repo2.update(id, data2, session=s), ])

"},{"location":"#mongo_ops.TransactionManager.start_session","title":"start_session async classmethod","text":"
start_session(\n    **kwargs: Any,\n) -> AbstractAsyncContextManager[AsyncIOMotorClientSession]\n

Start a transaction session as an async context manager.

Notes

Yields the active session with a started transaction; callers run their operations against the session inside the with-block.

Usage

async with TransactionManager.start_session() as session: await collection.insert_one(doc, session=session) await other_collection.update_one(filter, update, session=session)

"},{"location":"connection/","title":"Connection","text":""},{"location":"connection/#mongo_ops.connection","title":"mongo_ops.connection","text":""},{"location":"connection/#mongo_ops.connection--summary","title":"Summary","text":"

MongoDB connection management.

"},{"location":"connection/#mongo_ops.connection-classes","title":"Classes","text":""},{"location":"connection/#mongo_ops.connection.MongoConnectionManager","title":"MongoConnectionManager","text":"

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.

"},{"location":"connection/#mongo_ops.connection.MongoConnectionManager-functions","title":"Functions","text":""},{"location":"connection/#mongo_ops.connection.MongoConnectionManager.connect","title":"connect async classmethod","text":"
connect(\n    uri: str, db_name: str, **kwargs: Any\n) -> AsyncIOMotorDatabase\n

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.

"},{"location":"connection/#mongo_ops.connection.MongoConnectionManager.disconnect","title":"disconnect async classmethod","text":"
disconnect() -> None\n

Close the active MongoDB connection and cleanup resources.

"},{"location":"connection/#mongo_ops.connection.MongoConnectionManager.get_client","title":"get_client classmethod","text":"
get_client() -> AsyncIOMotorClient\n

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.

"},{"location":"connection/#mongo_ops.connection.MongoConnectionManager.get_database","title":"get_database classmethod","text":"
get_database() -> AsyncIOMotorDatabase\n

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.

"},{"location":"connection/#mongo_ops.connection.MongoConnectionManager.lifespan","title":"lifespan async classmethod","text":"
lifespan(\n    uri: str, db_name: str, **kwargs: Any\n) -> AbstractAsyncContextManager[AsyncIOMotorDatabase]\n

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

"},{"location":"models/","title":"Models","text":""},{"location":"models/#mongo_ops.models","title":"mongo_ops.models","text":""},{"location":"models/#mongo_ops.models--summary","title":"Summary","text":"

Base document models for MongoDB.

"},{"location":"models/#mongo_ops.models-classes","title":"Classes","text":""},{"location":"models/#mongo_ops.models.BaseDocument","title":"BaseDocument","text":"

Bases: BaseModel

Base document class with common MongoDB fields.

Inherit from this class to create Pydantic models that represent MongoDB documents. It includes automatic handling of the _id field and timestamps.

Attributes:

Name Type Description id PyObjectId | None

The MongoDB document ID (aliased to _id).

created_at datetime

Timestamp when the document was created.

updated_at datetime

Timestamp when the document was last updated.

"},{"location":"models/#mongo_ops.models.PyObjectId","title":"PyObjectId","text":"

Bases: ObjectId

Custom ObjectId type compatible with Pydantic v2.

This class extends the standard BSON ObjectId to provide validation and serialization support within Pydantic models.

"},{"location":"models/#mongo_ops.models.PyObjectId-functions","title":"Functions","text":""},{"location":"models/#mongo_ops.models.PyObjectId.__get_pydantic_core_schema__","title":"__get_pydantic_core_schema__ classmethod","text":"
__get_pydantic_core_schema__(\n    source_type: Any, handler: GetCoreSchemaHandler\n) -> Any\n

Define the core schema for Pydantic v2 validation and serialization.

"},{"location":"models/#mongo_ops.models.PyObjectId.__get_pydantic_json_schema__","title":"__get_pydantic_json_schema__ classmethod","text":"
__get_pydantic_json_schema__(\n    schema: Any, handler: Any\n) -> Any\n

Update the JSON schema for OpenAPI/Swagger documentation.

"},{"location":"models/#mongo_ops.models.PyObjectId.validate","title":"validate classmethod","text":"
validate(v: Any) -> ObjectId\n

Validate the input value and convert it to an ObjectId if possible.

Parameters:

Name Type Description Default v Any

The value to validate (can be str or ObjectId).

required

Returns:

Name Type Description ObjectId ObjectId

The validated ObjectId instance.

Raises:

Type Description ValueError

If the value is not a valid ObjectId.

"},{"location":"registry/","title":"Registry","text":""},{"location":"registry/#mongo_ops.registry","title":"mongo_ops.registry","text":""},{"location":"registry/#mongo_ops.registry--summary","title":"Summary","text":"

Model registration for multi-service initialization.

"},{"location":"registry/#mongo_ops.registry-classes","title":"Classes","text":""},{"location":"registry/#mongo_ops.registry.ModelRegistry","title":"ModelRegistry","text":"

Registry for managing multiple models and their collections.

This registry allows central management of collections and their associated indexes, making it easier to perform mass initialization at application startup.

"},{"location":"registry/#mongo_ops.registry.ModelRegistry-functions","title":"Functions","text":""},{"location":"registry/#mongo_ops.registry.ModelRegistry.get_cache_backend","title":"get_cache_backend classmethod","text":"
get_cache_backend() -> CacheBackend | None\n

Get the registered cache backend instance.

Returns:

Type Description CacheBackend | None

Optional[CacheBackend]: The cache backend, if registered.

"},{"location":"registry/#mongo_ops.registry.ModelRegistry.get_model","title":"get_model classmethod","text":"
get_model(collection_name: str) -> type[BaseDocument]\n

Retrieve a registered model by its collection name.

Parameters:

Name Type Description Default collection_name str

The name of the collection.

required

Returns:

Type Description type[BaseDocument]

type[BaseDocument]: The registered model class.

Raises:

Type Description KeyError

If the model for the given collection is not registered.

"},{"location":"registry/#mongo_ops.registry.ModelRegistry.initialize_all","title":"initialize_all async classmethod","text":"
initialize_all(\n    db: AsyncIOMotorDatabase | None = None,\n) -> None\n

Initialize all registered collections and create indexes.

This method should be called during application startup to ensure all necessary indexes exist in the database.

Parameters:

Name Type Description Default db Optional[AsyncIOMotorDatabase]

Database instance. If not provided, uses the global database from MongoConnectionManager.

None"},{"location":"registry/#mongo_ops.registry.ModelRegistry.initialize_cache","title":"initialize_cache async classmethod","text":"
initialize_cache() -> None\n

Initialize the registered cache backend.

Must be called after set_cache_backend() and before any cache-backed repository operations. Typically called right after MongoDB connection is established.

Raises:

Type Description RuntimeError

If no cache backend has been registered.

"},{"location":"registry/#mongo_ops.registry.ModelRegistry.list_collections","title":"list_collections classmethod","text":"
list_collections() -> list[str]\n

List all registered collection names.

Returns:

Type Description list[str]

list[str]: A list of collection names.

"},{"location":"registry/#mongo_ops.registry.ModelRegistry.register","title":"register classmethod","text":"
register(\n    collection_name: str,\n    model: type[BaseDocument],\n    indexes: list[tuple] | None = None,\n) -> None\n

Register a model with its collection and indexes.

Parameters:

Name Type Description Default collection_name str

Name of the MongoDB collection.

required model type[BaseDocument]

Document model class (subclass of BaseDocument).

required indexes list[Any]

List of index specifications. Each spec is passed directly to pymongo's create_index. Supported forms: - single field: (\"email\", 1) - compound: [(\"author_id\", 1), (\"created_at\", -1)] - with options: {\"keys\": [(\"username\", 1)], \"options\": {\"unique\": True}}

None Example

ModelRegistry.register(\"users\", UserDocument, indexes=[(\"email\", 1)]) ModelRegistry.register( \"posts\", PostDocument, indexes=[[(\"author_id\", 1), (\"created_at\", -1)]], )

"},{"location":"registry/#mongo_ops.registry.ModelRegistry.set_cache_backend","title":"set_cache_backend classmethod","text":"
set_cache_backend(backend: CacheBackend) -> None\n

Register a cache backend for all cache-enabled repositories.

Should be called after MongoDB connection is established, before cache-backed repositories are used.

Parameters:

Name Type Description Default backend CacheBackend

A CacheBackend instance (InMemoryCacheBackend or RedisCacheBackend).

required"},{"location":"registry/#mongo_ops.registry.ModelRegistry.shutdown_cache","title":"shutdown_cache async classmethod","text":"
shutdown_cache() -> None\n

Shutdown the registered cache backend gracefully.

Should be called during application shutdown to clean up background tasks (e.g., in-memory TTL cleanup).

"},{"location":"repository/","title":"Repository","text":""},{"location":"repository/#mongo_ops.repository","title":"mongo_ops.repository","text":""},{"location":"repository/#mongo_ops.repository--summary","title":"Summary","text":"

Repository patterns and CRUD mixins for MongoDB.

"},{"location":"repository/#mongo_ops.repository-classes","title":"Classes","text":""},{"location":"repository/#mongo_ops.repository.BaseRepository","title":"BaseRepository","text":"
BaseRepository(collection_name: str, model: type[T])\n

Bases: CRUDMixin[T], Generic[T]

Base repository class combining CRUD operations and collection management.

This class simplifies repository creation by automatically obtaining the database connection and collection instance.

Attributes:

Name Type Description collection_name str

The name of the collection managed by this repository.

Initialize the repository.

Parameters:

Name Type Description Default collection_name str

The name of the MongoDB collection.

required model type[T]

The Pydantic model class.

required"},{"location":"repository/#mongo_ops.repository.BaseRepository-functions","title":"Functions","text":""},{"location":"repository/#mongo_ops.repository.BaseRepository.count","title":"count async","text":"
count(filter: dict[str, Any] | None = None) -> int\n

Count documents matching a filter.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary.

None

Returns:

Name Type Description int int

The number of matching documents.

"},{"location":"repository/#mongo_ops.repository.BaseRepository.create","title":"create async","text":"
create(data: T) -> T\n

Create a new document in the collection.

Parameters:

Name Type Description Default data T

The Pydantic model instance to insert.

required

Returns:

Name Type Description T T

The created Pydantic model instance, including the assigned ID.

"},{"location":"repository/#mongo_ops.repository.BaseRepository.delete","title":"delete async","text":"
delete(id: str | ObjectId) -> bool\n

Delete a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Name Type Description bool bool

True if a document was deleted, False otherwise.

"},{"location":"repository/#mongo_ops.repository.BaseRepository.get_by_id","title":"get_by_id async","text":"
get_by_id(id: str | ObjectId) -> T | None\n

Retrieve a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Type Description T | None

Optional[T]: The Pydantic model instance if found, else None.

"},{"location":"repository/#mongo_ops.repository.BaseRepository.get_many","title":"get_many async","text":"
get_many(\n    filter: dict[str, Any] | None = None,\n    skip: int = 0,\n    limit: int = 100,\n    sort: list[tuple] | None = None,\n) -> list[T]\n

Retrieve multiple documents with filtering, pagination, and sorting.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary (e.g., {\"is_active\": True}).

None skip int

Number of documents to skip for pagination.

0 limit int

Maximum number of documents to return (default 100).

100 sort Optional[List[tuple]]

List of sort specifications [(field, direction), ...]. E.g., [(\"created_at\", -1)] for descending.

None

Returns:

Type Description list[T]

List[T]: A list of Pydantic model instances.

Example
users = await repo.get_many(\n    filter={\"role\": \"admin\"},\n    limit=10,\n    sort=[(\"username\", 1)]\n)\n
"},{"location":"repository/#mongo_ops.repository.BaseRepository.patch","title":"patch async","text":"
patch(id: str | ObjectId, data: dict[str, Any]) -> T | None\n

Partially update a document using $set (REST PATCH semantics).

Unlike update(), patch() takes a partial dict and applies only those fields. PopulatingRepository overrides this to prevent patching FK fields.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required data Dict[str, Any]

A partial dictionary of fields and values to update.

required

Returns:

Type Description T | None

Optional[T]: The updated Pydantic model instance if found, else None.

"},{"location":"repository/#mongo_ops.repository.BaseRepository.update","title":"update async","text":"
update(\n    id: str | ObjectId, data: dict[str, Any]\n) -> T | None\n

Update a document by its ID using the $set operator.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required data Dict[str, Any]

A dictionary of fields and values to update.

required

Returns:

Type Description T | None

Optional[T]: The updated Pydantic model instance if found, else None.

Example
updated_user = await repo.update(user_id, {\"email\": \"new@example.com\"})\n
"},{"location":"repository/#mongo_ops.repository.CRUDMixin","title":"CRUDMixin","text":"
CRUDMixin(\n    collection: AsyncIOMotorCollection, model: type[T]\n)\n

Bases: Generic[T]

Generic CRUD operations mixin for MongoDB collections.

This mixin provides standard Create, Read, Update, and Delete operations that work with Pydantic models.

Attributes:

Name Type Description collection AsyncIOMotorCollection

The Motor collection instance.

model type[T]

The Pydantic model class representing the document.

Initialize the CRUD mixin.

Parameters:

Name Type Description Default collection AsyncIOMotorCollection

The Motor collection to operate on.

required model type[T]

The Pydantic model class (subclass of BaseDocument).

required"},{"location":"repository/#mongo_ops.repository.CRUDMixin-functions","title":"Functions","text":""},{"location":"repository/#mongo_ops.repository.CRUDMixin.count","title":"count async","text":"
count(filter: dict[str, Any] | None = None) -> int\n

Count documents matching a filter.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary.

None

Returns:

Name Type Description int int

The number of matching documents.

"},{"location":"repository/#mongo_ops.repository.CRUDMixin.create","title":"create async","text":"
create(data: T) -> T\n

Create a new document in the collection.

Parameters:

Name Type Description Default data T

The Pydantic model instance to insert.

required

Returns:

Name Type Description T T

The created Pydantic model instance, including the assigned ID.

"},{"location":"repository/#mongo_ops.repository.CRUDMixin.delete","title":"delete async","text":"
delete(id: str | ObjectId) -> bool\n

Delete a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Name Type Description bool bool

True if a document was deleted, False otherwise.

"},{"location":"repository/#mongo_ops.repository.CRUDMixin.get_by_id","title":"get_by_id async","text":"
get_by_id(id: str | ObjectId) -> T | None\n

Retrieve a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Type Description T | None

Optional[T]: The Pydantic model instance if found, else None.

"},{"location":"repository/#mongo_ops.repository.CRUDMixin.get_many","title":"get_many async","text":"
get_many(\n    filter: dict[str, Any] | None = None,\n    skip: int = 0,\n    limit: int = 100,\n    sort: list[tuple] | None = None,\n) -> list[T]\n

Retrieve multiple documents with filtering, pagination, and sorting.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary (e.g., {\"is_active\": True}).

None skip int

Number of documents to skip for pagination.

0 limit int

Maximum number of documents to return (default 100).

100 sort Optional[List[tuple]]

List of sort specifications [(field, direction), ...]. E.g., [(\"created_at\", -1)] for descending.

None

Returns:

Type Description list[T]

List[T]: A list of Pydantic model instances.

Example
users = await repo.get_many(\n    filter={\"role\": \"admin\"},\n    limit=10,\n    sort=[(\"username\", 1)]\n)\n
"},{"location":"repository/#mongo_ops.repository.CRUDMixin.patch","title":"patch async","text":"
patch(id: str | ObjectId, data: dict[str, Any]) -> T | None\n

Partially update a document using $set (REST PATCH semantics).

Unlike update(), patch() takes a partial dict and applies only those fields. PopulatingRepository overrides this to prevent patching FK fields.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required data Dict[str, Any]

A partial dictionary of fields and values to update.

required

Returns:

Type Description T | None

Optional[T]: The updated Pydantic model instance if found, else None.

"},{"location":"repository/#mongo_ops.repository.CRUDMixin.update","title":"update async","text":"
update(\n    id: str | ObjectId, data: dict[str, Any]\n) -> T | None\n

Update a document by its ID using the $set operator.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required data Dict[str, Any]

A dictionary of fields and values to update.

required

Returns:

Type Description T | None

Optional[T]: The updated Pydantic model instance if found, else None.

Example
updated_user = await repo.update(user_id, {\"email\": \"new@example.com\"})\n
"},{"location":"repository/#mongo_ops.repository.PopulatingRepository","title":"PopulatingRepository","text":"
PopulatingRepository(\n    collection_name: str,\n    model: type[T],\n    population_engine: PopulationEngine | None = None,\n    populate_rules: list[PopulateRule] | None = None,\n)\n

Bases: BaseRepository[T], Generic[T]

Repository that auto-populates and depopulates FK references.

On read, ObjectId FK fields are resolved to model instances according to the configured PopulateRules. On write, populated model references are collapsed back to ObjectIds before hitting MongoDB.

Notes

Guarantees:

- Populate rules apply on both read (data_to_model) and write\n  (create/update) paths.\n- Patching FK fields via patch() is rejected.\n- Class attributes `population_engine` and `_populate_rules` must\n  be set (see set_population_engine/set_populate_rules) for any\n  population to occur.\n

Initialize the repository.

Parameters:

Name Type Description Default collection_name str

Name of the MongoDB collection.

required model type[T]

The Pydantic model class.

required population_engine Optional[PopulationEngine]

Engine used to resolve references. Defaults to None.

None populate_rules Optional[list[PopulateRule]]

Rules describing FK resolution. Defaults to None (no rules).

None"},{"location":"repository/#mongo_ops.repository.PopulatingRepository-functions","title":"Functions","text":""},{"location":"repository/#mongo_ops.repository.PopulatingRepository.count","title":"count async","text":"
count(filter: dict[str, Any] | None = None) -> int\n

Count documents matching a filter.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary.

None

Returns:

Name Type Description int int

The number of matching documents.

"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.create","title":"create async","text":"
create(data: T) -> T\n

Depopulate, insert, and re-populate a new document.

Parameters:

Name Type Description Default data T

The model instance to insert (FK fields may hold models).

required

Returns:

Name Type Description T T

The created model instance, including its ID.

"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.data_to_model","title":"data_to_model async","text":"
data_to_model(data: dict) -> T\n

Convert a raw dict to a model, resolving FK references first.

Parameters:

Name Type Description Default data dict

Raw document dictionary.

required

Returns:

Name Type Description T T

The populated model instance.

Raises:

Type Description ValueError

If a FK field holds an embedded dict instead of an ObjectId.

"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.delete","title":"delete async","text":"
delete(id: str | ObjectId) -> bool\n

Delete a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Name Type Description bool bool

True if a document was deleted, False otherwise.

"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.get_by_id","title":"get_by_id async","text":"
get_by_id(id: str | ObjectId) -> T | None\n

Retrieve a document by its ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required

Returns:

Type Description T | None

Optional[T]: The Pydantic model instance if found, else None.

"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.get_many","title":"get_many async","text":"
get_many(\n    filter: dict[str, Any] | None = None,\n    skip: int = 0,\n    limit: int = 100,\n    sort: list[tuple] | None = None,\n) -> list[T]\n

Retrieve multiple documents with filtering, pagination, and sorting.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary (e.g., {\"is_active\": True}).

None skip int

Number of documents to skip for pagination.

0 limit int

Maximum number of documents to return (default 100).

100 sort Optional[List[tuple]]

List of sort specifications [(field, direction), ...]. E.g., [(\"created_at\", -1)] for descending.

None

Returns:

Type Description list[T]

List[T]: A list of Pydantic model instances.

Example
users = await repo.get_many(\n    filter={\"role\": \"admin\"},\n    limit=10,\n    sort=[(\"username\", 1)]\n)\n
"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.patch","title":"patch async","text":"
patch(id: str | ObjectId, data: dict[str, Any]) -> T | None\n

Partially update a document, rejecting FK field changes.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID.

required data dict[str, Any]

Partial dictionary of fields to update.

required

Returns:

Type Description T | None

Optional[T]: The updated model instance, or None when not found.

Raises:

Type Description ValueError

If any FK field is present in the patch payload.

"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.set_populate_rules","title":"set_populate_rules","text":"
set_populate_rules(rules: list[PopulateRule]) -> None\n

Set the FK resolution rules.

Parameters:

Name Type Description Default rules list[PopulateRule]

Rules describing which fields resolve and how deep.

required"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.set_population_engine","title":"set_population_engine","text":"
set_population_engine(engine: PopulationEngine) -> None\n

Attach (or replace) the population engine.

Parameters:

Name Type Description Default engine PopulationEngine

Engine used to resolve references.

required"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.update","title":"update async","text":"
update(id: str | ObjectId, data: T) -> T | None\n

Depopulate and update a document by ID.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID.

required data T

The model instance holding the updated fields.

required

Returns:

Type Description T | None

Optional[T]: The updated model instance, or None when not found.

"},{"location":"transactions/","title":"Transactions","text":""},{"location":"transactions/#mongo_ops.transactions","title":"mongo_ops.transactions","text":""},{"location":"transactions/#mongo_ops.transactions--summary","title":"Summary","text":"

Transaction management helpers for MongoDB.

"},{"location":"transactions/#mongo_ops.transactions-classes","title":"Classes","text":""},{"location":"transactions/#mongo_ops.transactions.TransactionManager","title":"TransactionManager","text":"

Simplified multi-document transaction handling.

This class provides helpers for executing operations within a MongoDB transaction, ensuring ACID compliance for multi-document updates.

"},{"location":"transactions/#mongo_ops.transactions.TransactionManager-functions","title":"Functions","text":""},{"location":"transactions/#mongo_ops.transactions.TransactionManager.execute_transaction","title":"execute_transaction async classmethod","text":"
execute_transaction(\n    operations: list[\n        Callable[\n            [AsyncIOMotorClientSession], Awaitable[Any]\n        ]\n    ],\n    **kwargs: Any\n) -> list[Any]\n

Execute multiple operations within a single transaction.

Parameters:

Name Type Description Default operations List[Callable[[AsyncIOMotorClientSession], Awaitable[Any]]]

A list of async callables that accept a session parameter and return a result.

required **kwargs Any

Transaction options.

{}

Returns:

Type Description list[Any]

List[Any]: A list containing the results of each operation.

Example

results = await TransactionManager.execute_transaction([ lambda s: repo1.create(data1, session=s), lambda s: repo2.update(id, data2, session=s), ])

"},{"location":"transactions/#mongo_ops.transactions.TransactionManager.start_session","title":"start_session async classmethod","text":"
start_session(\n    **kwargs: Any,\n) -> AbstractAsyncContextManager[AsyncIOMotorClientSession]\n

Start a transaction session as an async context manager.

Notes

Yields the active session with a started transaction; callers run their operations against the session inside the with-block.

Usage

async with TransactionManager.start_session() as session: await collection.insert_one(doc, session=session) await other_collection.update_one(filter, update, session=session)

"},{"location":"cache/","title":"Cache","text":""},{"location":"cache/#mongo_ops.cache","title":"mongo_ops.cache","text":""},{"location":"cache/#mongo_ops.cache--summary","title":"Summary","text":"

Cache backends and configuration for mongo-ops.

"},{"location":"cache/#mongo_ops.cache-classes","title":"Classes","text":""},{"location":"cache/#mongo_ops.cache.CacheBackend","title":"CacheBackend","text":"

Bases: ABC

Abstract interface for cache backends.

Implementations store byte-encoded values keyed by string, track usage statistics, and manage their own lifecycle. The in-memory and Redis backends both implement this contract.

"},{"location":"cache/#mongo_ops.cache.CacheBackend-functions","title":"Functions","text":""},{"location":"cache/#mongo_ops.cache.CacheBackend.clear_pattern","title":"clear_pattern abstractmethod async","text":"
clear_pattern(pattern: str) -> None\n

Remove all keys matching a glob pattern.

Parameters:

Name Type Description Default pattern str

Glob-style pattern; a trailing * matches prefixes.

required"},{"location":"cache/#mongo_ops.cache.CacheBackend.delete","title":"delete abstractmethod async","text":"
delete(key: str) -> None\n

Remove a key from the cache.

Parameters:

Name Type Description Default key str

The cache key.

required"},{"location":"cache/#mongo_ops.cache.CacheBackend.exists","title":"exists abstractmethod async","text":"
exists(key: str) -> bool\n

Check whether a key is present.

Parameters:

Name Type Description Default key str

The cache key.

required

Returns:

Name Type Description bool bool

True if the key exists, False otherwise.

"},{"location":"cache/#mongo_ops.cache.CacheBackend.get","title":"get abstractmethod async","text":"
get(key: str) -> bytes | None\n

Fetch a value from the cache.

Parameters:

Name Type Description Default key str

The cache key.

required

Returns:

Type Description bytes | None

Optional[bytes]: The cached bytes, or None on a miss.

"},{"location":"cache/#mongo_ops.cache.CacheBackend.get_stats","title":"get_stats abstractmethod async","text":"
get_stats() -> CacheStats\n

Return a snapshot of cache statistics.

Returns:

Name Type Description CacheStats CacheStats

A copy of the current stats counters.

"},{"location":"cache/#mongo_ops.cache.CacheBackend.initialize","title":"initialize abstractmethod async","text":"
initialize() -> None\n

Start background resources owned by the backend.

Should be called once during application startup, after the repositories are connected.

"},{"location":"cache/#mongo_ops.cache.CacheBackend.set","title":"set abstractmethod async","text":"
set(key: str, value: bytes, ttl: int | None = None) -> None\n

Store a value in the cache.

Parameters:

Name Type Description Default key str

The cache key.

required value bytes

The byte-encoded value to store.

required ttl Optional[int]

Time-to-live in seconds. When None, the backend default applies.

None"},{"location":"cache/#mongo_ops.cache.CacheBackend.shutdown","title":"shutdown abstractmethod async","text":"
shutdown() -> None\n

Stop and release background resources.

Should be called once during application shutdown.

"},{"location":"cache/#mongo_ops.cache.CacheConfig","title":"CacheConfig dataclass","text":"
CacheConfig(\n    enabled: bool = True,\n    backend: Literal[\"memory\", \"redis\"] = \"memory\",\n    redis_client: Redis | None = None,\n    default_ttl: int = 300,\n    max_entries: int = 10000,\n    key_prefix: str = \"\",\n    cleanup_interval: int = 60,\n)\n

Configuration for the cached repository layer.

Attributes:

Name Type Description enabled bool

Whether caching is active for the repository.

backend Literal['memory', 'redis']

Which backend to use. Defaults to \"memory\".

redis_client Optional[Redis]

Redis client required when backend is \"redis\".

default_ttl int

Default time-to-live for cached entries, in seconds.

max_entries int

Maximum entries for the in-memory backend.

key_prefix str

Prefix applied to cache keys; defaults to the collection name when empty.

cleanup_interval int

Interval (seconds) for the in-memory expiry sweep.

"},{"location":"cache/#mongo_ops.cache.CacheConfig-functions","title":"Functions","text":""},{"location":"cache/#mongo_ops.cache.CacheConfig.__post_init__","title":"__post_init__","text":"
__post_init__() -> None\n

Validate backend/redis consistency.

Raises:

Type Description ValueError

If the backend is \"redis\" and no client is given.

ImportError

If the redis package is not installed.

"},{"location":"cache/#mongo_ops.cache.CacheStats","title":"CacheStats dataclass","text":"
CacheStats(\n    hits: int = 0,\n    misses: int = 0,\n    sets: int = 0,\n    deletes: int = 0,\n    current_size: int = 0,\n    max_size: int = 0,\n)\n

Snapshot of cache usage and activity counters.

Attributes:

Name Type Description hits int

Number of get() calls that found a value.

misses int

Number of get() calls that returned None.

sets int

Number of values written to the cache.

deletes int

Number of keys removed.

current_size int

Number of entries currently held.

max_size int

Maximum number of entries the cache allows (0 = unbounded).

"},{"location":"cache/#mongo_ops.cache.CircularReferenceError","title":"CircularReferenceError","text":"
CircularReferenceError(\n    collection: str, doc_id: ObjectId, path: list[str]\n)\n

Bases: ValueError

Raised when population detects a cycle in the reference graph.

Attributes:

Name Type Description collection str

Collection where the cycle was detected.

doc_id ObjectId

Document ID where the cycle was detected.

path list[str]

Ordered labels describing the visited reference path.

Initialize the error with cycle metadata.

Parameters:

Name Type Description Default collection str

Collection where the cycle was detected.

required doc_id ObjectId

Document ID where the cycle was detected.

required path list[str]

Ordered labels describing the visited reference path.

required"},{"location":"cache/#mongo_ops.cache.CircularReferenceError-functions","title":"Functions","text":""},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend","title":"InMemoryCacheBackend","text":"
InMemoryCacheBackend(\n    max_entries: int = 10000,\n    default_ttl: int = 300,\n    cleanup_interval: int = 60,\n)\n

Bases: CacheBackend

Cache backend backed by an in-memory dict with TTL expiry.

Entries are stored in an OrderedDict for LRU-compatible eviction and a min-heap of expiry timestamps drives periodic removal of stale entries.

Notes

Thread safety:

All operations take an asyncio lock; the backend is safe for\nconcurrent use within a single event loop.\n

Initialize the backend.

Parameters:

Name Type Description Default max_entries int

Maximum number of entries before LRU eviction kicks in.

10000 default_ttl int

Default time-to-live for entries, in seconds.

300 cleanup_interval int

Seconds between periodic expired-entry sweeps.

60"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend-functions","title":"Functions","text":""},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.clear_pattern","title":"clear_pattern async","text":"
clear_pattern(pattern: str) -> None\n

Remove all keys matching a glob pattern.

Parameters:

Name Type Description Default pattern str

Glob-style pattern; a trailing * matches prefixes.

required"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.delete","title":"delete async","text":"
delete(key: str) -> None\n

Remove a key from the cache.

Parameters:

Name Type Description Default key str

The cache key.

required"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.exists","title":"exists async","text":"
exists(key: str) -> bool\n

Check whether a key is present.

Parameters:

Name Type Description Default key str

The cache key.

required

Returns:

Name Type Description bool bool

True if the key exists, False otherwise.

"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.get","title":"get async","text":"
get(key: str) -> bytes | None\n

Fetch a value from the cache.

Parameters:

Name Type Description Default key str

The cache key.

required

Returns:

Type Description bytes | None

Optional[bytes]: The cached bytes, or None on a miss.

"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.get_stats","title":"get_stats async","text":"
get_stats() -> CacheStats\n

Return a snapshot of cache statistics.

Returns:

Name Type Description CacheStats CacheStats

A copy of the current stats counters.

"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.initialize","title":"initialize async","text":"
initialize() -> None\n

Start the periodic expired-entry cleanup task.

"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.set","title":"set async","text":"
set(key: str, value: bytes, ttl: int | None = None) -> None\n

Store a value in the cache.

Parameters:

Name Type Description Default key str

The cache key.

required value bytes

The byte-encoded value to store.

required ttl Optional[int]

Time-to-live in seconds; defaults to the backend default.

None"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Cancel and await the cleanup task.

"},{"location":"cache/backend/","title":"Backend","text":""},{"location":"cache/backend/#mongo_ops.cache.backend","title":"mongo_ops.cache.backend","text":""},{"location":"cache/backend/#mongo_ops.cache.backend--summary","title":"Summary","text":"

Cache backend abstraction.

"},{"location":"cache/backend/#mongo_ops.cache.backend-classes","title":"Classes","text":""},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend","title":"CacheBackend","text":"

Bases: ABC

Abstract interface for cache backends.

Implementations store byte-encoded values keyed by string, track usage statistics, and manage their own lifecycle. The in-memory and Redis backends both implement this contract.

"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend-functions","title":"Functions","text":""},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.clear_pattern","title":"clear_pattern abstractmethod async","text":"
clear_pattern(pattern: str) -> None\n

Remove all keys matching a glob pattern.

Parameters:

Name Type Description Default pattern str

Glob-style pattern; a trailing * matches prefixes.

required"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.delete","title":"delete abstractmethod async","text":"
delete(key: str) -> None\n

Remove a key from the cache.

Parameters:

Name Type Description Default key str

The cache key.

required"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.exists","title":"exists abstractmethod async","text":"
exists(key: str) -> bool\n

Check whether a key is present.

Parameters:

Name Type Description Default key str

The cache key.

required

Returns:

Name Type Description bool bool

True if the key exists, False otherwise.

"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.get","title":"get abstractmethod async","text":"
get(key: str) -> bytes | None\n

Fetch a value from the cache.

Parameters:

Name Type Description Default key str

The cache key.

required

Returns:

Type Description bytes | None

Optional[bytes]: The cached bytes, or None on a miss.

"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.get_stats","title":"get_stats abstractmethod async","text":"
get_stats() -> CacheStats\n

Return a snapshot of cache statistics.

Returns:

Name Type Description CacheStats CacheStats

A copy of the current stats counters.

"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.initialize","title":"initialize abstractmethod async","text":"
initialize() -> None\n

Start background resources owned by the backend.

Should be called once during application startup, after the repositories are connected.

"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.set","title":"set abstractmethod async","text":"
set(key: str, value: bytes, ttl: int | None = None) -> None\n

Store a value in the cache.

Parameters:

Name Type Description Default key str

The cache key.

required value bytes

The byte-encoded value to store.

required ttl Optional[int]

Time-to-live in seconds. When None, the backend default applies.

None"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.shutdown","title":"shutdown abstractmethod async","text":"
shutdown() -> None\n

Stop and release background resources.

Should be called once during application shutdown.

"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheStats","title":"CacheStats dataclass","text":"
CacheStats(\n    hits: int = 0,\n    misses: int = 0,\n    sets: int = 0,\n    deletes: int = 0,\n    current_size: int = 0,\n    max_size: int = 0,\n)\n

Snapshot of cache usage and activity counters.

Attributes:

Name Type Description hits int

Number of get() calls that found a value.

misses int

Number of get() calls that returned None.

sets int

Number of values written to the cache.

deletes int

Number of keys removed.

current_size int

Number of entries currently held.

max_size int

Maximum number of entries the cache allows (0 = unbounded).

"},{"location":"cache/backend/#mongo_ops.cache.backend.CircularReferenceError","title":"CircularReferenceError","text":"
CircularReferenceError(\n    collection: str, doc_id: ObjectId, path: list[str]\n)\n

Bases: ValueError

Raised when population detects a cycle in the reference graph.

Attributes:

Name Type Description collection str

Collection where the cycle was detected.

doc_id ObjectId

Document ID where the cycle was detected.

path list[str]

Ordered labels describing the visited reference path.

Initialize the error with cycle metadata.

Parameters:

Name Type Description Default collection str

Collection where the cycle was detected.

required doc_id ObjectId

Document ID where the cycle was detected.

required path list[str]

Ordered labels describing the visited reference path.

required"},{"location":"cache/backend/#mongo_ops.cache.backend.CircularReferenceError-functions","title":"Functions","text":""},{"location":"cache/config/","title":"Config","text":""},{"location":"cache/config/#mongo_ops.cache.config","title":"mongo_ops.cache.config","text":""},{"location":"cache/config/#mongo_ops.cache.config--summary","title":"Summary","text":"

Cache configuration.

"},{"location":"cache/config/#mongo_ops.cache.config-classes","title":"Classes","text":""},{"location":"cache/config/#mongo_ops.cache.config.CacheConfig","title":"CacheConfig dataclass","text":"
CacheConfig(\n    enabled: bool = True,\n    backend: Literal[\"memory\", \"redis\"] = \"memory\",\n    redis_client: Redis | None = None,\n    default_ttl: int = 300,\n    max_entries: int = 10000,\n    key_prefix: str = \"\",\n    cleanup_interval: int = 60,\n)\n

Configuration for the cached repository layer.

Attributes:

Name Type Description enabled bool

Whether caching is active for the repository.

backend Literal['memory', 'redis']

Which backend to use. Defaults to \"memory\".

redis_client Optional[Redis]

Redis client required when backend is \"redis\".

default_ttl int

Default time-to-live for cached entries, in seconds.

max_entries int

Maximum entries for the in-memory backend.

key_prefix str

Prefix applied to cache keys; defaults to the collection name when empty.

cleanup_interval int

Interval (seconds) for the in-memory expiry sweep.

"},{"location":"cache/config/#mongo_ops.cache.config.CacheConfig-functions","title":"Functions","text":""},{"location":"cache/config/#mongo_ops.cache.config.CacheConfig.__post_init__","title":"__post_init__","text":"
__post_init__() -> None\n

Validate backend/redis consistency.

Raises:

Type Description ValueError

If the backend is \"redis\" and no client is given.

ImportError

If the redis package is not installed.

"},{"location":"cache/in_memory/","title":"In Memory","text":""},{"location":"cache/in_memory/#mongo_ops.cache.in_memory","title":"mongo_ops.cache.in_memory","text":""},{"location":"cache/in_memory/#mongo_ops.cache.in_memory--summary","title":"Summary","text":"

In-memory cache backend with TTL-based eviction and encode/decode helpers.

"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory-classes","title":"Classes","text":""},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend","title":"InMemoryCacheBackend","text":"
InMemoryCacheBackend(\n    max_entries: int = 10000,\n    default_ttl: int = 300,\n    cleanup_interval: int = 60,\n)\n

Bases: CacheBackend

Cache backend backed by an in-memory dict with TTL expiry.

Entries are stored in an OrderedDict for LRU-compatible eviction and a min-heap of expiry timestamps drives periodic removal of stale entries.

Notes

Thread safety:

All operations take an asyncio lock; the backend is safe for\nconcurrent use within a single event loop.\n

Initialize the backend.

Parameters:

Name Type Description Default max_entries int

Maximum number of entries before LRU eviction kicks in.

10000 default_ttl int

Default time-to-live for entries, in seconds.

300 cleanup_interval int

Seconds between periodic expired-entry sweeps.

60"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend-functions","title":"Functions","text":""},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.clear_pattern","title":"clear_pattern async","text":"
clear_pattern(pattern: str) -> None\n

Remove all keys matching a glob pattern.

Parameters:

Name Type Description Default pattern str

Glob-style pattern; a trailing * matches prefixes.

required"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.delete","title":"delete async","text":"
delete(key: str) -> None\n

Remove a key from the cache.

Parameters:

Name Type Description Default key str

The cache key.

required"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.exists","title":"exists async","text":"
exists(key: str) -> bool\n

Check whether a key is present.

Parameters:

Name Type Description Default key str

The cache key.

required

Returns:

Name Type Description bool bool

True if the key exists, False otherwise.

"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.get","title":"get async","text":"
get(key: str) -> bytes | None\n

Fetch a value from the cache.

Parameters:

Name Type Description Default key str

The cache key.

required

Returns:

Type Description bytes | None

Optional[bytes]: The cached bytes, or None on a miss.

"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.get_stats","title":"get_stats async","text":"
get_stats() -> CacheStats\n

Return a snapshot of cache statistics.

Returns:

Name Type Description CacheStats CacheStats

A copy of the current stats counters.

"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.initialize","title":"initialize async","text":"
initialize() -> None\n

Start the periodic expired-entry cleanup task.

"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.set","title":"set async","text":"
set(key: str, value: bytes, ttl: int | None = None) -> None\n

Store a value in the cache.

Parameters:

Name Type Description Default key str

The cache key.

required value bytes

The byte-encoded value to store.

required ttl Optional[int]

Time-to-live in seconds; defaults to the backend default.

None"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Cancel and await the cleanup task.

"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory-functions","title":"Functions","text":""},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.decode_value","title":"decode_value","text":"
decode_value(data: bytes) -> dict\n

Decode cache bytes back into a dict.

Parameters:

Name Type Description Default data bytes

UTF-8 JSON bytes produced by encode_value().

required

Returns:

Name Type Description dict dict

The decoded dictionary.

"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.encode_value","title":"encode_value","text":"
encode_value(value: dict) -> bytes\n

Encode a dict into cache-ready bytes.

Non-serializable values (e.g., ObjectId) are coerced with str().

Parameters:

Name Type Description Default value dict

The dictionary to encode.

required

Returns:

Name Type Description bytes bytes

UTF-8 JSON bytes.

"},{"location":"cache/redis_backend/","title":"Redis Backend","text":""},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend","title":"mongo_ops.cache.redis_backend","text":""},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend--summary","title":"Summary","text":"

Redis cache backend with key prefixing and pub/sub invalidation.

"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend-classes","title":"Classes","text":""},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend","title":"RedisCacheBackend","text":"
RedisCacheBackend(\n    redis_client: Redis,\n    key_prefix: str = \"\",\n    default_ttl: int = 300,\n)\n

Bases: CacheBackend

Cache backend backed by Redis with key prefixing.

Values are stored with a configurable key prefix, and deletions publish on a shared invalidation channel so other processes can react.

Notes

Lifecycle:

Requires ``pip install mongo-ops[redis]`` and a live Redis\nconnection supplied by the caller.\n

Initialize the backend.

Parameters:

Name Type Description Default redis_client Redis

Asynchronous Redis client.

required key_prefix str

Prefix applied to all keys. Defaults to \"\".

'' default_ttl int

Default time-to-live for entries, in seconds.

300

Raises:

Type Description ImportError

If the redis package is not installed.

"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend-functions","title":"Functions","text":""},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.clear_pattern","title":"clear_pattern async","text":"
clear_pattern(pattern: str) -> None\n

Remove all keys matching a glob pattern via SCAN/DEL.

Parameters:

Name Type Description Default pattern str

Glob-style pattern; a trailing * matches prefixes.

required"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.delete","title":"delete async","text":"
delete(key: str) -> None\n

Remove a key and publish an invalidation notice.

Parameters:

Name Type Description Default key str

The cache key.

required"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.exists","title":"exists async","text":"
exists(key: str) -> bool\n

Check whether a key is present.

Parameters:

Name Type Description Default key str

The cache key.

required

Returns:

Name Type Description bool bool

True if the key exists, False otherwise.

"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.get","title":"get async","text":"
get(key: str) -> bytes | None\n

Fetch a value from the cache.

Parameters:

Name Type Description Default key str

The cache key.

required

Returns:

Type Description bytes | None

Optional[bytes]: The cached bytes, or None on a miss.

"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.get_stats","title":"get_stats async","text":"
get_stats() -> CacheStats\n

Return a snapshot of cache statistics.

Returns:

Name Type Description CacheStats CacheStats

Stats with current_size taken from Redis dbsize.

"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.initialize","title":"initialize async","text":"
initialize() -> None\n

Open the pub/sub subscription used for invalidation.

"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.publish_invalidate","title":"publish_invalidate async","text":"
publish_invalidate(key: str) -> None\n

Publish an invalidation notice for a key.

Parameters:

Name Type Description Default key str

The cache key to broadcast.

required"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.set","title":"set async","text":"
set(key: str, value: bytes, ttl: int | None = None) -> None\n

Store a value in the cache.

Parameters:

Name Type Description Default key str

The cache key.

required value bytes

The byte-encoded value to store.

required ttl Optional[int]

Time-to-live in seconds; defaults to the backend default.

None"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.shutdown","title":"shutdown async","text":"
shutdown() -> None\n

Close the pub/sub subscription.

"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend-functions","title":"Functions","text":""},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.decode_value","title":"decode_value","text":"
decode_value(data: bytes) -> dict\n

Decode cache bytes back into a dict.

Parameters:

Name Type Description Default data bytes

UTF-8 JSON bytes produced by encode_value().

required

Returns:

Name Type Description dict dict

The decoded dictionary.

"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.encode_value","title":"encode_value","text":"
encode_value(value: dict) -> bytes\n

Encode a dict into cache-ready bytes.

Non-serializable values (e.g., ObjectId) are coerced with str().

Parameters:

Name Type Description Default value dict

The dictionary to encode.

required

Returns:

Name Type Description bytes bytes

UTF-8 JSON bytes.

"},{"location":"cache/repository/","title":"Repository","text":""},{"location":"cache/repository/#mongo_ops.cache.repository","title":"mongo_ops.cache.repository","text":""},{"location":"cache/repository/#mongo_ops.cache.repository--summary","title":"Summary","text":"

Cached repository layer that combines a repository with a cache backend.

"},{"location":"cache/repository/#mongo_ops.cache.repository-classes","title":"Classes","text":""},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository","title":"CachedBaseRepository","text":"
CachedBaseRepository(\n    collection_name: str,\n    model: type[T],\n    cache_backend: CacheBackend,\n    config: CacheConfig | None = None,\n)\n

Bases: BaseRepository[T], Generic[T]

Repository that reads and writes through a cache backend.

Wraps an existing BaseRepository with an ID-keyed cache. Reads consult the backend first and fall through to MongoDB on a miss, populating the cache on success. Writes invalidate or refresh the affected key.

Notes

Guarantees:

- The cache holds the raw document shape (``model_dump``), so FK\n  references round-trip as hex strings, not populated models.\n- When ``config.enabled`` is False the repository behaves exactly\n  like its parent with no cache access.\n

Initialize the cached repository.

Parameters:

Name Type Description Default collection_name str

Name of the MongoDB collection.

required model type[T]

The Pydantic model class.

required cache_backend CacheBackend

Backend used to store and fetch entries.

required config Optional[CacheConfig]

Cache configuration; a default CacheConfig is used when None.

None"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository-functions","title":"Functions","text":""},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.count","title":"count async","text":"
count(filter: dict[str, Any] | None = None) -> int\n

Count documents matching a filter.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary.

None

Returns:

Name Type Description int int

The number of matching documents.

"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.create","title":"create async","text":"
create(data: T) -> T\n

Insert a document and cache the raw snapshot.

Parameters:

Name Type Description Default data T

The model instance to insert.

required

Returns:

Name Type Description T T

The created model instance, including its ID.

"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.delete","title":"delete async","text":"
delete(id: str | ObjectId) -> bool\n

Delete a document and remove its cache entry.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID.

required

Returns:

Name Type Description bool bool

True if a document was deleted, False otherwise.

"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.get_by_id","title":"get_by_id async","text":"
get_by_id(id: str | ObjectId) -> T | None\n

Fetch a document, reading through the cache when enabled.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID.

required

Returns:

Type Description T | None

Optional[T]: The model instance, or None when not found.

"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.get_many","title":"get_many async","text":"
get_many(\n    filter: dict[str, Any] | None = None,\n    skip: int = 0,\n    limit: int = 100,\n    sort: list[tuple] | None = None,\n) -> list[T]\n

Retrieve multiple documents with filtering, pagination, and sorting.

Parameters:

Name Type Description Default filter Optional[Dict[str, Any]]

MongoDB filter dictionary (e.g., {\"is_active\": True}).

None skip int

Number of documents to skip for pagination.

0 limit int

Maximum number of documents to return (default 100).

100 sort Optional[List[tuple]]

List of sort specifications [(field, direction), ...]. E.g., [(\"created_at\", -1)] for descending.

None

Returns:

Type Description list[T]

List[T]: A list of Pydantic model instances.

Example
users = await repo.get_many(\n    filter={\"role\": \"admin\"},\n    limit=10,\n    sort=[(\"username\", 1)]\n)\n
"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.invalidate_cache","title":"invalidate_cache async","text":"
invalidate_cache(id: str | ObjectId) -> None\n

Remove a single document's cache entry.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID to invalidate.

required"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.patch","title":"patch async","text":"
patch(id: str | ObjectId, data: dict[str, Any]) -> T | None\n

Partially update a document using $set (REST PATCH semantics).

Unlike update(), patch() takes a partial dict and applies only those fields. PopulatingRepository overrides this to prevent patching FK fields.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID (string or ObjectId).

required data Dict[str, Any]

A partial dictionary of fields and values to update.

required

Returns:

Type Description T | None

Optional[T]: The updated Pydantic model instance if found, else None.

"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.update","title":"update async","text":"
update(id: str | ObjectId, data: dict) -> T | None\n

Update a document and refresh its cache entry.

Parameters:

Name Type Description Default id Union[str, ObjectId]

The document ID.

required data dict

Fields to set via $set.

required

Returns:

Type Description T | None

Optional[T]: The updated model instance, or None when not found.

"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.warm_cache","title":"warm_cache async","text":"
warm_cache(ids: list[str | ObjectId]) -> int\n

Pre-populate the cache for a set of document IDs.

Docs already present in the cache are skipped.

Parameters:

Name Type Description Default ids list[Union[str, ObjectId]]

Document IDs to warm.

required

Returns:

Name Type Description int int

Number of entries added to the cache.

"},{"location":"cache/repository/#mongo_ops.cache.repository-functions","title":"Functions","text":""},{"location":"populate/","title":"Populate","text":""},{"location":"populate/#mongo_ops.populate","title":"mongo_ops.populate","text":""},{"location":"populate/#mongo_ops.populate--summary","title":"Summary","text":"

Document populating rules and population engine.

"},{"location":"populate/#mongo_ops.populate-classes","title":"Classes","text":""},{"location":"populate/#mongo_ops.populate.PopulateRule","title":"PopulateRule dataclass","text":"
PopulateRule(\n    field_name: str,\n    collection_name: str,\n    nested_rules: list[PopulateRule] | None = None,\n    max_depth: int = 1,\n    filter: dict[str, Any] | None = None,\n    projection: dict[str, Any] | None = None,\n)\n

Describes how a foreign-key field resolves to another collection.

A rule declares the field to resolve, the collection its references point at, and optional nested rules applied to the referenced document itself. It also bounds how deep the resolution may recurse.

Attributes:

Name Type Description field_name str

Name of the FK field on the source document.

collection_name str

Collection the reference points into.

nested_rules Optional[list[PopulateRule]]

Sub-rules applied to the referenced document. Defaults to None.

max_depth int

Maximum recursion depth for this rule. Defaults to 1.

filter Optional[dict[str, Any]]

Optional Mongo filter applied when fetching the reference. Defaults to None.

projection Optional[dict[str, Any]]

Optional Mongo projection applied when fetching the reference. Defaults to None.

"},{"location":"populate/#mongo_ops.populate.PopulationEngine","title":"PopulationEngine","text":"
PopulationEngine(\n    repos: dict[str, Any], global_max_depth: int = 10\n)\n

Resolves FK references across collections with cycle detection.

The engine holds a registry of repositories keyed by collection name and walks documents according to PopulateRules, resolving ObjectId references into model instances. A visited-path set guards against circular graphs.

Notes

Guarantees:

- A reference that cannot be resolved becomes None (scalar) or a\n  None entry (list) rather than raising.\n- Depth is capped by both per-rule max_depth and a global\n  global_max_depth.\n

Initialize the engine.

Parameters:

Name Type Description Default repos dict[str, Any]

Mapping of collection name to repository, used to fetch referenced documents.

required global_max_depth int

Hard cap on overall population recursion depth. Defaults to 10.

10"},{"location":"populate/#mongo_ops.populate.PopulationEngine-functions","title":"Functions","text":""},{"location":"populate/#mongo_ops.populate.PopulationEngine.depopulate","title":"depopulate async","text":"
depopulate(document: T, rules: list[PopulateRule]) -> T\n

Collapse populated model references back to their ObjectIds.

This is the inverse of populate(): model-valued FK fields are reduced to stored identifiers before the document is written to MongoDB.

Parameters:

Name Type Description Default document T

The document to depopulate in place.

required rules list[PopulateRule]

Rules describing which fields to collapse.

required

Returns:

Name Type Description T T

The depopulated document.

Raises:

Type Description AttributeError

If a list entry is not a BaseDocument where expected.

"},{"location":"populate/#mongo_ops.populate.PopulationEngine.populate","title":"populate async","text":"
populate(\n    document: T,\n    rules: list[PopulateRule],\n    depth: int = 0,\n    _visited: set[tuple[str, str]] | None = None,\n    _path: list[str] | None = None,\n) -> T\n

Resolve FK fields on a document according to the given rules.

Parameters:

Name Type Description Default document T

The document to populate in place.

required rules list[PopulateRule]

Rules describing which fields to resolve and how deep.

required depth int

Current recursion depth. Defaults to 0.

0 _visited Optional[set[tuple[str, str]]]

Internal set of (class, id) pairs on the active path.

None _path Optional[list[str]]

Internal path labels used for cycle reporting.

None

Returns:

Name Type Description T T

The populated document.

Raises:

Type Description CircularReferenceError

If a cycle is detected on the active path.

"},{"location":"populate/#mongo_ops.populate.PopulationEngine.register_repo","title":"register_repo","text":"
register_repo(collection_name: str, repo: Any) -> None\n

Register or replace the repository for a collection.

Parameters:

Name Type Description Default collection_name str

Collection the repository manages.

required repo Any

Repository exposing get_by_id() used to resolve references.

required"},{"location":"populate/engine/","title":"Engine","text":""},{"location":"populate/engine/#mongo_ops.populate.engine","title":"mongo_ops.populate.engine","text":""},{"location":"populate/engine/#mongo_ops.populate.engine--summary","title":"Summary","text":"

Recursive document population engine with cycle detection.

"},{"location":"populate/engine/#mongo_ops.populate.engine-classes","title":"Classes","text":""},{"location":"populate/engine/#mongo_ops.populate.engine.PopulationEngine","title":"PopulationEngine","text":"
PopulationEngine(\n    repos: dict[str, Any], global_max_depth: int = 10\n)\n

Resolves FK references across collections with cycle detection.

The engine holds a registry of repositories keyed by collection name and walks documents according to PopulateRules, resolving ObjectId references into model instances. A visited-path set guards against circular graphs.

Notes

Guarantees:

- A reference that cannot be resolved becomes None (scalar) or a\n  None entry (list) rather than raising.\n- Depth is capped by both per-rule max_depth and a global\n  global_max_depth.\n

Initialize the engine.

Parameters:

Name Type Description Default repos dict[str, Any]

Mapping of collection name to repository, used to fetch referenced documents.

required global_max_depth int

Hard cap on overall population recursion depth. Defaults to 10.

10"},{"location":"populate/engine/#mongo_ops.populate.engine.PopulationEngine-functions","title":"Functions","text":""},{"location":"populate/engine/#mongo_ops.populate.engine.PopulationEngine.depopulate","title":"depopulate async","text":"
depopulate(document: T, rules: list[PopulateRule]) -> T\n

Collapse populated model references back to their ObjectIds.

This is the inverse of populate(): model-valued FK fields are reduced to stored identifiers before the document is written to MongoDB.

Parameters:

Name Type Description Default document T

The document to depopulate in place.

required rules list[PopulateRule]

Rules describing which fields to collapse.

required

Returns:

Name Type Description T T

The depopulated document.

Raises:

Type Description AttributeError

If a list entry is not a BaseDocument where expected.

"},{"location":"populate/engine/#mongo_ops.populate.engine.PopulationEngine.populate","title":"populate async","text":"
populate(\n    document: T,\n    rules: list[PopulateRule],\n    depth: int = 0,\n    _visited: set[tuple[str, str]] | None = None,\n    _path: list[str] | None = None,\n) -> T\n

Resolve FK fields on a document according to the given rules.

Parameters:

Name Type Description Default document T

The document to populate in place.

required rules list[PopulateRule]

Rules describing which fields to resolve and how deep.

required depth int

Current recursion depth. Defaults to 0.

0 _visited Optional[set[tuple[str, str]]]

Internal set of (class, id) pairs on the active path.

None _path Optional[list[str]]

Internal path labels used for cycle reporting.

None

Returns:

Name Type Description T T

The populated document.

Raises:

Type Description CircularReferenceError

If a cycle is detected on the active path.

"},{"location":"populate/engine/#mongo_ops.populate.engine.PopulationEngine.register_repo","title":"register_repo","text":"
register_repo(collection_name: str, repo: Any) -> None\n

Register or replace the repository for a collection.

Parameters:

Name Type Description Default collection_name str

Collection the repository manages.

required repo Any

Repository exposing get_by_id() used to resolve references.

required"},{"location":"populate/rules/","title":"Rules","text":""},{"location":"populate/rules/#mongo_ops.populate.rules","title":"mongo_ops.populate.rules","text":""},{"location":"populate/rules/#mongo_ops.populate.rules--summary","title":"Summary","text":"

Populate rules describing which foreign-key fields to resolve.

"},{"location":"populate/rules/#mongo_ops.populate.rules-classes","title":"Classes","text":""},{"location":"populate/rules/#mongo_ops.populate.rules.PopulateRule","title":"PopulateRule dataclass","text":"
PopulateRule(\n    field_name: str,\n    collection_name: str,\n    nested_rules: list[PopulateRule] | None = None,\n    max_depth: int = 1,\n    filter: dict[str, Any] | None = None,\n    projection: dict[str, Any] | None = None,\n)\n

Describes how a foreign-key field resolves to another collection.

A rule declares the field to resolve, the collection its references point at, and optional nested rules applied to the referenced document itself. It also bounds how deep the resolution may recurse.

Attributes:

Name Type Description field_name str

Name of the FK field on the source document.

collection_name str

Collection the reference points into.

nested_rules Optional[list[PopulateRule]]

Sub-rules applied to the referenced document. Defaults to None.

max_depth int

Maximum recursion depth for this rule. Defaults to 1.

filter Optional[dict[str, Any]]

Optional Mongo filter applied when fetching the reference. Defaults to None.

projection Optional[dict[str, Any]]

Optional Mongo projection applied when fetching the reference. Defaults to None.

"}]}