{"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:
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 Descriptionid 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 Descriptioncollection_name str The name of the collection managed by this repository.
Initialize the repository.
Parameters:
Name Type Description Defaultcollection_name str The name of the MongoDB collection.
requiredmodel type[T] The Pydantic model class.
required"},{"location":"#mongo_ops.BaseRepository-functions","title":"Functions","text":""},{"location":"#mongo_ops.BaseRepository.count","title":"countasync","text":"count(filter: dict[str, Any] | None = None) -> int\n Count documents matching a filter.
Parameters:
Name Type Description Defaultfilter Optional[Dict[str, Any]] MongoDB filter dictionary.
None Returns:
Name Type Descriptionint int The number of matching documents.
"},{"location":"#mongo_ops.BaseRepository.create","title":"createasync","text":"create(data: T) -> T\n Create a new document in the collection.
Parameters:
Name Type Description Defaultdata T The Pydantic model instance to insert.
requiredReturns:
Name Type DescriptionT T The created Pydantic model instance, including the assigned ID.
"},{"location":"#mongo_ops.BaseRepository.delete","title":"deleteasync","text":"delete(id: str | ObjectId) -> bool\n Delete a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Name Type Descriptionbool bool True if a document was deleted, False otherwise.
"},{"location":"#mongo_ops.BaseRepository.get_by_id","title":"get_by_idasync","text":"get_by_id(id: str | ObjectId) -> T | None\n Retrieve a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Type DescriptionT | None Optional[T]: The Pydantic model instance if found, else None.
"},{"location":"#mongo_ops.BaseRepository.get_many","title":"get_manyasync","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 Defaultfilter 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 Descriptionlist[T] List[T]: A list of Pydantic model instances.
Exampleusers = 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 Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requireddata Dict[str, Any] A partial dictionary of fields and values to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated Pydantic model instance if found, else None.
"},{"location":"#mongo_ops.BaseRepository.update","title":"updateasync","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 Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requireddata Dict[str, Any] A dictionary of fields and values to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated Pydantic model instance if found, else None.
Exampleupdated_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 Descriptioncollection AsyncIOMotorCollection The Motor collection instance.
model type[T] The Pydantic model class representing the document.
Initialize the CRUD mixin.
Parameters:
Name Type Description Defaultcollection AsyncIOMotorCollection The Motor collection to operate on.
requiredmodel type[T] The Pydantic model class (subclass of BaseDocument).
required"},{"location":"#mongo_ops.CRUDMixin-functions","title":"Functions","text":""},{"location":"#mongo_ops.CRUDMixin.count","title":"countasync","text":"count(filter: dict[str, Any] | None = None) -> int\n Count documents matching a filter.
Parameters:
Name Type Description Defaultfilter Optional[Dict[str, Any]] MongoDB filter dictionary.
None Returns:
Name Type Descriptionint int The number of matching documents.
"},{"location":"#mongo_ops.CRUDMixin.create","title":"createasync","text":"create(data: T) -> T\n Create a new document in the collection.
Parameters:
Name Type Description Defaultdata T The Pydantic model instance to insert.
requiredReturns:
Name Type DescriptionT T The created Pydantic model instance, including the assigned ID.
"},{"location":"#mongo_ops.CRUDMixin.delete","title":"deleteasync","text":"delete(id: str | ObjectId) -> bool\n Delete a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Name Type Descriptionbool bool True if a document was deleted, False otherwise.
"},{"location":"#mongo_ops.CRUDMixin.get_by_id","title":"get_by_idasync","text":"get_by_id(id: str | ObjectId) -> T | None\n Retrieve a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Type DescriptionT | None Optional[T]: The Pydantic model instance if found, else None.
"},{"location":"#mongo_ops.CRUDMixin.get_many","title":"get_manyasync","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 Defaultfilter 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 Descriptionlist[T] List[T]: A list of Pydantic model instances.
Exampleusers = 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 Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requireddata Dict[str, Any] A partial dictionary of fields and values to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated Pydantic model instance if found, else None.
"},{"location":"#mongo_ops.CRUDMixin.update","title":"updateasync","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 Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requireddata Dict[str, Any] A dictionary of fields and values to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated Pydantic model instance if found, else None.
Exampleupdated_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.
NotesGuarantees:
- 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 Defaultcollection_name str Name of the MongoDB collection.
requiredmodel type[T] The Pydantic model class.
requiredcache_backend CacheBackend Backend used to store and fetch entries.
requiredconfig 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 Defaultfilter Optional[Dict[str, Any]] MongoDB filter dictionary.
None Returns:
Name Type Descriptionint int The number of matching documents.
"},{"location":"#mongo_ops.CachedBaseRepository.create","title":"createasync","text":"create(data: T) -> T\n Insert a document and cache the raw snapshot.
Parameters:
Name Type Description Defaultdata T The model instance to insert.
requiredReturns:
Name Type DescriptionT T The created model instance, including its ID.
"},{"location":"#mongo_ops.CachedBaseRepository.delete","title":"deleteasync","text":"delete(id: str | ObjectId) -> bool\n Delete a document and remove its cache entry.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID.
requiredReturns:
Name Type Descriptionbool bool True if a document was deleted, False otherwise.
"},{"location":"#mongo_ops.CachedBaseRepository.get_by_id","title":"get_by_idasync","text":"get_by_id(id: str | ObjectId) -> T | None\n Fetch a document, reading through the cache when enabled.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID.
requiredReturns:
Type DescriptionT | None Optional[T]: The model instance, or None when not found.
"},{"location":"#mongo_ops.CachedBaseRepository.get_many","title":"get_manyasync","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 Defaultfilter 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 Descriptionlist[T] List[T]: A list of Pydantic model instances.
Exampleusers = 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 Defaultid Union[str, ObjectId] The document ID to invalidate.
required"},{"location":"#mongo_ops.CachedBaseRepository.patch","title":"patchasync","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 Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requireddata Dict[str, Any] A partial dictionary of fields and values to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated Pydantic model instance if found, else None.
"},{"location":"#mongo_ops.CachedBaseRepository.update","title":"updateasync","text":"update(id: str | ObjectId, data: dict) -> T | None\n Update a document and refresh its cache entry.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID.
requireddata dict Fields to set via $set.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated model instance, or None when not found.
"},{"location":"#mongo_ops.CachedBaseRepository.warm_cache","title":"warm_cacheasync","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 Defaultids list[Union[str, ObjectId]] Document IDs to warm.
requiredReturns:
Name Type Descriptionint 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_backendclassmethod","text":"get_cache_backend() -> CacheBackend | None\n Get the registered cache backend instance.
Returns:
Type DescriptionCacheBackend | None Optional[CacheBackend]: The cache backend, if registered.
"},{"location":"#mongo_ops.ModelRegistry.get_model","title":"get_modelclassmethod","text":"get_model(collection_name: str) -> type[BaseDocument]\n Retrieve a registered model by its collection name.
Parameters:
Name Type Description Defaultcollection_name str The name of the collection.
requiredReturns:
Type Descriptiontype[BaseDocument] type[BaseDocument]: The registered model class.
Raises:
Type DescriptionKeyError If the model for the given collection is not registered.
"},{"location":"#mongo_ops.ModelRegistry.initialize_all","title":"initialize_allasync 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 Defaultdb 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 DescriptionRuntimeError If no cache backend has been registered.
"},{"location":"#mongo_ops.ModelRegistry.list_collections","title":"list_collectionsclassmethod","text":"list_collections() -> list[str]\n List all registered collection names.
Returns:
Type Descriptionlist[str] list[str]: A list of collection names.
"},{"location":"#mongo_ops.ModelRegistry.register","title":"registerclassmethod","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 Defaultcollection_name str Name of the MongoDB collection.
requiredmodel type[BaseDocument] Document model class (subclass of BaseDocument).
requiredindexes 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_backendclassmethod","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 Defaultbackend CacheBackend A CacheBackend instance (InMemoryCacheBackend or RedisCacheBackend).
required"},{"location":"#mongo_ops.ModelRegistry.shutdown_cache","title":"shutdown_cacheasync 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":"connectasync 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 Defaulturi str MongoDB connection URI (e.g., \"mongodb://localhost:27017\").
requireddb_name str Name of the database to use.
required**kwargs Any Additional Motor client options (e.g., maxPoolSize).
{} Returns:
Name Type DescriptionAsyncIOMotorDatabase AsyncIOMotorDatabase The initialized database instance.
"},{"location":"#mongo_ops.MongoConnectionManager.disconnect","title":"disconnectasync classmethod","text":"disconnect() -> None\n Close the active MongoDB connection and cleanup resources.
"},{"location":"#mongo_ops.MongoConnectionManager.get_client","title":"get_clientclassmethod","text":"get_client() -> AsyncIOMotorClient\n Retrieve the current client instance.
Returns:
Name Type DescriptionAsyncIOMotorClient AsyncIOMotorClient The active Motor client instance.
Raises:
Type DescriptionRuntimeError If connect() has not been called yet.
"},{"location":"#mongo_ops.MongoConnectionManager.get_database","title":"get_databaseclassmethod","text":"get_database() -> AsyncIOMotorDatabase\n Retrieve the current database instance.
Returns:
Name Type DescriptionAsyncIOMotorDatabase AsyncIOMotorDatabase The active database instance.
Raises:
Type DescriptionRuntimeError If connect() has not been called yet.
"},{"location":"#mongo_ops.MongoConnectionManager.lifespan","title":"lifespanasync 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.
NotesConnects 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.
NotesGuarantees:
- 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 Defaultcollection_name str Name of the MongoDB collection.
requiredmodel type[T] The Pydantic model class.
requiredpopulation_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 Defaultfilter Optional[Dict[str, Any]] MongoDB filter dictionary.
None Returns:
Name Type Descriptionint int The number of matching documents.
"},{"location":"#mongo_ops.PopulatingRepository.create","title":"createasync","text":"create(data: T) -> T\n Depopulate, insert, and re-populate a new document.
Parameters:
Name Type Description Defaultdata T The model instance to insert (FK fields may hold models).
requiredReturns:
Name Type DescriptionT T The created model instance, including its ID.
"},{"location":"#mongo_ops.PopulatingRepository.data_to_model","title":"data_to_modelasync","text":"data_to_model(data: dict) -> T\n Convert a raw dict to a model, resolving FK references first.
Parameters:
Name Type Description Defaultdata dict Raw document dictionary.
requiredReturns:
Name Type DescriptionT T The populated model instance.
Raises:
Type DescriptionValueError If a FK field holds an embedded dict instead of an ObjectId.
"},{"location":"#mongo_ops.PopulatingRepository.delete","title":"deleteasync","text":"delete(id: str | ObjectId) -> bool\n Delete a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Name Type Descriptionbool bool True if a document was deleted, False otherwise.
"},{"location":"#mongo_ops.PopulatingRepository.get_by_id","title":"get_by_idasync","text":"get_by_id(id: str | ObjectId) -> T | None\n Retrieve a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Type DescriptionT | None Optional[T]: The Pydantic model instance if found, else None.
"},{"location":"#mongo_ops.PopulatingRepository.get_many","title":"get_manyasync","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 Defaultfilter 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 Descriptionlist[T] List[T]: A list of Pydantic model instances.
Exampleusers = 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 Defaultid Union[str, ObjectId] The document ID.
requireddata dict[str, Any] Partial dictionary of fields to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated model instance, or None when not found.
Raises:
Type DescriptionValueError 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 Defaultrules 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 Defaultengine PopulationEngine Engine used to resolve references.
required"},{"location":"#mongo_ops.PopulatingRepository.update","title":"updateasync","text":"update(id: str | ObjectId, data: T) -> T | None\n Depopulate and update a document by ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID.
requireddata T The model instance holding the updated fields.
requiredReturns:
Type DescriptionT | 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_transactionasync 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 Defaultoperations 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 Descriptionlist[Any] List[Any]: A list containing the results of each operation.
Exampleresults = 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_sessionasync classmethod","text":"start_session(\n **kwargs: Any,\n) -> AbstractAsyncContextManager[AsyncIOMotorClientSession]\n Start a transaction session as an async context manager.
NotesYields the active session with a started transaction; callers run their operations against the session inside the with-block.
Usageasync 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":"connectasync 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 Defaulturi str MongoDB connection URI (e.g., \"mongodb://localhost:27017\").
requireddb_name str Name of the database to use.
required**kwargs Any Additional Motor client options (e.g., maxPoolSize).
{} Returns:
Name Type DescriptionAsyncIOMotorDatabase AsyncIOMotorDatabase The initialized database instance.
"},{"location":"connection/#mongo_ops.connection.MongoConnectionManager.disconnect","title":"disconnectasync classmethod","text":"disconnect() -> None\n Close the active MongoDB connection and cleanup resources.
"},{"location":"connection/#mongo_ops.connection.MongoConnectionManager.get_client","title":"get_clientclassmethod","text":"get_client() -> AsyncIOMotorClient\n Retrieve the current client instance.
Returns:
Name Type DescriptionAsyncIOMotorClient AsyncIOMotorClient The active Motor client instance.
Raises:
Type DescriptionRuntimeError If connect() has not been called yet.
"},{"location":"connection/#mongo_ops.connection.MongoConnectionManager.get_database","title":"get_databaseclassmethod","text":"get_database() -> AsyncIOMotorDatabase\n Retrieve the current database instance.
Returns:
Name Type DescriptionAsyncIOMotorDatabase AsyncIOMotorDatabase The active database instance.
Raises:
Type DescriptionRuntimeError If connect() has not been called yet.
"},{"location":"connection/#mongo_ops.connection.MongoConnectionManager.lifespan","title":"lifespanasync 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.
NotesConnects 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 Descriptionid 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":"validateclassmethod","text":"validate(v: Any) -> ObjectId\n Validate the input value and convert it to an ObjectId if possible.
Parameters:
Name Type Description Defaultv Any The value to validate (can be str or ObjectId).
requiredReturns:
Name Type DescriptionObjectId ObjectId The validated ObjectId instance.
Raises:
Type DescriptionValueError 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_backendclassmethod","text":"get_cache_backend() -> CacheBackend | None\n Get the registered cache backend instance.
Returns:
Type DescriptionCacheBackend | None Optional[CacheBackend]: The cache backend, if registered.
"},{"location":"registry/#mongo_ops.registry.ModelRegistry.get_model","title":"get_modelclassmethod","text":"get_model(collection_name: str) -> type[BaseDocument]\n Retrieve a registered model by its collection name.
Parameters:
Name Type Description Defaultcollection_name str The name of the collection.
requiredReturns:
Type Descriptiontype[BaseDocument] type[BaseDocument]: The registered model class.
Raises:
Type DescriptionKeyError If the model for the given collection is not registered.
"},{"location":"registry/#mongo_ops.registry.ModelRegistry.initialize_all","title":"initialize_allasync 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 Defaultdb 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 DescriptionRuntimeError If no cache backend has been registered.
"},{"location":"registry/#mongo_ops.registry.ModelRegistry.list_collections","title":"list_collectionsclassmethod","text":"list_collections() -> list[str]\n List all registered collection names.
Returns:
Type Descriptionlist[str] list[str]: A list of collection names.
"},{"location":"registry/#mongo_ops.registry.ModelRegistry.register","title":"registerclassmethod","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 Defaultcollection_name str Name of the MongoDB collection.
requiredmodel type[BaseDocument] Document model class (subclass of BaseDocument).
requiredindexes 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_backendclassmethod","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 Defaultbackend CacheBackend A CacheBackend instance (InMemoryCacheBackend or RedisCacheBackend).
required"},{"location":"registry/#mongo_ops.registry.ModelRegistry.shutdown_cache","title":"shutdown_cacheasync 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 Descriptioncollection_name str The name of the collection managed by this repository.
Initialize the repository.
Parameters:
Name Type Description Defaultcollection_name str The name of the MongoDB collection.
requiredmodel 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":"countasync","text":"count(filter: dict[str, Any] | None = None) -> int\n Count documents matching a filter.
Parameters:
Name Type Description Defaultfilter Optional[Dict[str, Any]] MongoDB filter dictionary.
None Returns:
Name Type Descriptionint int The number of matching documents.
"},{"location":"repository/#mongo_ops.repository.BaseRepository.create","title":"createasync","text":"create(data: T) -> T\n Create a new document in the collection.
Parameters:
Name Type Description Defaultdata T The Pydantic model instance to insert.
requiredReturns:
Name Type DescriptionT T The created Pydantic model instance, including the assigned ID.
"},{"location":"repository/#mongo_ops.repository.BaseRepository.delete","title":"deleteasync","text":"delete(id: str | ObjectId) -> bool\n Delete a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Name Type Descriptionbool bool True if a document was deleted, False otherwise.
"},{"location":"repository/#mongo_ops.repository.BaseRepository.get_by_id","title":"get_by_idasync","text":"get_by_id(id: str | ObjectId) -> T | None\n Retrieve a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Type DescriptionT | None Optional[T]: The Pydantic model instance if found, else None.
"},{"location":"repository/#mongo_ops.repository.BaseRepository.get_many","title":"get_manyasync","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 Defaultfilter 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 Descriptionlist[T] List[T]: A list of Pydantic model instances.
Exampleusers = 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 Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requireddata Dict[str, Any] A partial dictionary of fields and values to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated Pydantic model instance if found, else None.
"},{"location":"repository/#mongo_ops.repository.BaseRepository.update","title":"updateasync","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 Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requireddata Dict[str, Any] A dictionary of fields and values to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated Pydantic model instance if found, else None.
Exampleupdated_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 Descriptioncollection AsyncIOMotorCollection The Motor collection instance.
model type[T] The Pydantic model class representing the document.
Initialize the CRUD mixin.
Parameters:
Name Type Description Defaultcollection AsyncIOMotorCollection The Motor collection to operate on.
requiredmodel 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":"countasync","text":"count(filter: dict[str, Any] | None = None) -> int\n Count documents matching a filter.
Parameters:
Name Type Description Defaultfilter Optional[Dict[str, Any]] MongoDB filter dictionary.
None Returns:
Name Type Descriptionint int The number of matching documents.
"},{"location":"repository/#mongo_ops.repository.CRUDMixin.create","title":"createasync","text":"create(data: T) -> T\n Create a new document in the collection.
Parameters:
Name Type Description Defaultdata T The Pydantic model instance to insert.
requiredReturns:
Name Type DescriptionT T The created Pydantic model instance, including the assigned ID.
"},{"location":"repository/#mongo_ops.repository.CRUDMixin.delete","title":"deleteasync","text":"delete(id: str | ObjectId) -> bool\n Delete a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Name Type Descriptionbool bool True if a document was deleted, False otherwise.
"},{"location":"repository/#mongo_ops.repository.CRUDMixin.get_by_id","title":"get_by_idasync","text":"get_by_id(id: str | ObjectId) -> T | None\n Retrieve a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Type DescriptionT | None Optional[T]: The Pydantic model instance if found, else None.
"},{"location":"repository/#mongo_ops.repository.CRUDMixin.get_many","title":"get_manyasync","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 Defaultfilter 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 Descriptionlist[T] List[T]: A list of Pydantic model instances.
Exampleusers = 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 Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requireddata Dict[str, Any] A partial dictionary of fields and values to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated Pydantic model instance if found, else None.
"},{"location":"repository/#mongo_ops.repository.CRUDMixin.update","title":"updateasync","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 Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requireddata Dict[str, Any] A dictionary of fields and values to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated Pydantic model instance if found, else None.
Exampleupdated_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.
NotesGuarantees:
- 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 Defaultcollection_name str Name of the MongoDB collection.
requiredmodel type[T] The Pydantic model class.
requiredpopulation_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 Defaultfilter Optional[Dict[str, Any]] MongoDB filter dictionary.
None Returns:
Name Type Descriptionint int The number of matching documents.
"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.create","title":"createasync","text":"create(data: T) -> T\n Depopulate, insert, and re-populate a new document.
Parameters:
Name Type Description Defaultdata T The model instance to insert (FK fields may hold models).
requiredReturns:
Name Type DescriptionT T The created model instance, including its ID.
"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.data_to_model","title":"data_to_modelasync","text":"data_to_model(data: dict) -> T\n Convert a raw dict to a model, resolving FK references first.
Parameters:
Name Type Description Defaultdata dict Raw document dictionary.
requiredReturns:
Name Type DescriptionT T The populated model instance.
Raises:
Type DescriptionValueError If a FK field holds an embedded dict instead of an ObjectId.
"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.delete","title":"deleteasync","text":"delete(id: str | ObjectId) -> bool\n Delete a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Name Type Descriptionbool bool True if a document was deleted, False otherwise.
"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.get_by_id","title":"get_by_idasync","text":"get_by_id(id: str | ObjectId) -> T | None\n Retrieve a document by its ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requiredReturns:
Type DescriptionT | None Optional[T]: The Pydantic model instance if found, else None.
"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.get_many","title":"get_manyasync","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 Defaultfilter 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 Descriptionlist[T] List[T]: A list of Pydantic model instances.
Exampleusers = 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 Defaultid Union[str, ObjectId] The document ID.
requireddata dict[str, Any] Partial dictionary of fields to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated model instance, or None when not found.
Raises:
Type DescriptionValueError 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 Defaultrules 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 Defaultengine PopulationEngine Engine used to resolve references.
required"},{"location":"repository/#mongo_ops.repository.PopulatingRepository.update","title":"updateasync","text":"update(id: str | ObjectId, data: T) -> T | None\n Depopulate and update a document by ID.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID.
requireddata T The model instance holding the updated fields.
requiredReturns:
Type DescriptionT | 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_transactionasync 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 Defaultoperations 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 Descriptionlist[Any] List[Any]: A list containing the results of each operation.
Exampleresults = 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_sessionasync classmethod","text":"start_session(\n **kwargs: Any,\n) -> AbstractAsyncContextManager[AsyncIOMotorClientSession]\n Start a transaction session as an async context manager.
NotesYields the active session with a started transaction; callers run their operations against the session inside the with-block.
Usageasync 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_patternabstractmethod async","text":"clear_pattern(pattern: str) -> None\n Remove all keys matching a glob pattern.
Parameters:
Name Type Description Defaultpattern str Glob-style pattern; a trailing * matches prefixes.
abstractmethod async","text":"delete(key: str) -> None\n Remove a key from the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
required"},{"location":"cache/#mongo_ops.cache.CacheBackend.exists","title":"existsabstractmethod async","text":"exists(key: str) -> bool\n Check whether a key is present.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredReturns:
Name Type Descriptionbool bool True if the key exists, False otherwise.
"},{"location":"cache/#mongo_ops.cache.CacheBackend.get","title":"getabstractmethod async","text":"get(key: str) -> bytes | None\n Fetch a value from the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredReturns:
Type Descriptionbytes | None Optional[bytes]: The cached bytes, or None on a miss.
"},{"location":"cache/#mongo_ops.cache.CacheBackend.get_stats","title":"get_statsabstractmethod async","text":"get_stats() -> CacheStats\n Return a snapshot of cache statistics.
Returns:
Name Type DescriptionCacheStats CacheStats A copy of the current stats counters.
"},{"location":"cache/#mongo_ops.cache.CacheBackend.initialize","title":"initializeabstractmethod 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":"setabstractmethod async","text":"set(key: str, value: bytes, ttl: int | None = None) -> None\n Store a value in the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredvalue bytes The byte-encoded value to store.
requiredttl 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":"CacheConfigdataclass","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 Descriptionenabled 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 DescriptionValueError 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":"CacheStatsdataclass","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 Descriptionhits 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 Descriptioncollection 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 Defaultcollection str Collection where the cycle was detected.
requireddoc_id ObjectId Document ID where the cycle was detected.
requiredpath 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.
NotesThread 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 Defaultmax_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 Defaultpattern str Glob-style pattern; a trailing * matches prefixes.
async","text":"delete(key: str) -> None\n Remove a key from the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
required"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.exists","title":"existsasync","text":"exists(key: str) -> bool\n Check whether a key is present.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredReturns:
Name Type Descriptionbool bool True if the key exists, False otherwise.
"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.get","title":"getasync","text":"get(key: str) -> bytes | None\n Fetch a value from the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredReturns:
Type Descriptionbytes | None Optional[bytes]: The cached bytes, or None on a miss.
"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.get_stats","title":"get_statsasync","text":"get_stats() -> CacheStats\n Return a snapshot of cache statistics.
Returns:
Name Type DescriptionCacheStats CacheStats A copy of the current stats counters.
"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.initialize","title":"initializeasync","text":"initialize() -> None\n Start the periodic expired-entry cleanup task.
"},{"location":"cache/#mongo_ops.cache.InMemoryCacheBackend.set","title":"setasync","text":"set(key: str, value: bytes, ttl: int | None = None) -> None\n Store a value in the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredvalue bytes The byte-encoded value to store.
requiredttl 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_patternabstractmethod async","text":"clear_pattern(pattern: str) -> None\n Remove all keys matching a glob pattern.
Parameters:
Name Type Description Defaultpattern str Glob-style pattern; a trailing * matches prefixes.
abstractmethod async","text":"delete(key: str) -> None\n Remove a key from the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
required"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.exists","title":"existsabstractmethod async","text":"exists(key: str) -> bool\n Check whether a key is present.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredReturns:
Name Type Descriptionbool bool True if the key exists, False otherwise.
"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.get","title":"getabstractmethod async","text":"get(key: str) -> bytes | None\n Fetch a value from the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredReturns:
Type Descriptionbytes | None Optional[bytes]: The cached bytes, or None on a miss.
"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.get_stats","title":"get_statsabstractmethod async","text":"get_stats() -> CacheStats\n Return a snapshot of cache statistics.
Returns:
Name Type DescriptionCacheStats CacheStats A copy of the current stats counters.
"},{"location":"cache/backend/#mongo_ops.cache.backend.CacheBackend.initialize","title":"initializeabstractmethod 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":"setabstractmethod async","text":"set(key: str, value: bytes, ttl: int | None = None) -> None\n Store a value in the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredvalue bytes The byte-encoded value to store.
requiredttl 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":"CacheStatsdataclass","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 Descriptionhits 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 Descriptioncollection 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 Defaultcollection str Collection where the cycle was detected.
requireddoc_id ObjectId Document ID where the cycle was detected.
requiredpath 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":"CacheConfigdataclass","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 Descriptionenabled 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 DescriptionValueError 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.
NotesThread 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 Defaultmax_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 Defaultpattern str Glob-style pattern; a trailing * matches prefixes.
async","text":"delete(key: str) -> None\n Remove a key from the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
required"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.exists","title":"existsasync","text":"exists(key: str) -> bool\n Check whether a key is present.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredReturns:
Name Type Descriptionbool bool True if the key exists, False otherwise.
"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.get","title":"getasync","text":"get(key: str) -> bytes | None\n Fetch a value from the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredReturns:
Type Descriptionbytes | 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_statsasync","text":"get_stats() -> CacheStats\n Return a snapshot of cache statistics.
Returns:
Name Type DescriptionCacheStats CacheStats A copy of the current stats counters.
"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.initialize","title":"initializeasync","text":"initialize() -> None\n Start the periodic expired-entry cleanup task.
"},{"location":"cache/in_memory/#mongo_ops.cache.in_memory.InMemoryCacheBackend.set","title":"setasync","text":"set(key: str, value: bytes, ttl: int | None = None) -> None\n Store a value in the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredvalue bytes The byte-encoded value to store.
requiredttl 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 Defaultdata bytes UTF-8 JSON bytes produced by encode_value().
requiredReturns:
Name Type Descriptiondict 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 Defaultvalue dict The dictionary to encode.
requiredReturns:
Name Type Descriptionbytes 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.
NotesLifecycle:
Requires ``pip install mongo-ops[redis]`` and a live Redis\nconnection supplied by the caller.\n Initialize the backend.
Parameters:
Name Type Description Defaultredis_client Redis Asynchronous Redis client.
requiredkey_prefix str Prefix applied to all keys. Defaults to \"\".
'' default_ttl int Default time-to-live for entries, in seconds.
300 Raises:
Type DescriptionImportError 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_patternasync","text":"clear_pattern(pattern: str) -> None\n Remove all keys matching a glob pattern via SCAN/DEL.
Parameters:
Name Type Description Defaultpattern str Glob-style pattern; a trailing * matches prefixes.
async","text":"delete(key: str) -> None\n Remove a key and publish an invalidation notice.
Parameters:
Name Type Description Defaultkey str The cache key.
required"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.exists","title":"existsasync","text":"exists(key: str) -> bool\n Check whether a key is present.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredReturns:
Name Type Descriptionbool bool True if the key exists, False otherwise.
"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.get","title":"getasync","text":"get(key: str) -> bytes | None\n Fetch a value from the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredReturns:
Type Descriptionbytes | 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_statsasync","text":"get_stats() -> CacheStats\n Return a snapshot of cache statistics.
Returns:
Name Type DescriptionCacheStats CacheStats Stats with current_size taken from Redis dbsize.
"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.initialize","title":"initializeasync","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_invalidateasync","text":"publish_invalidate(key: str) -> None\n Publish an invalidation notice for a key.
Parameters:
Name Type Description Defaultkey str The cache key to broadcast.
required"},{"location":"cache/redis_backend/#mongo_ops.cache.redis_backend.RedisCacheBackend.set","title":"setasync","text":"set(key: str, value: bytes, ttl: int | None = None) -> None\n Store a value in the cache.
Parameters:
Name Type Description Defaultkey str The cache key.
requiredvalue bytes The byte-encoded value to store.
requiredttl 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 Defaultdata bytes UTF-8 JSON bytes produced by encode_value().
requiredReturns:
Name Type Descriptiondict 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 Defaultvalue dict The dictionary to encode.
requiredReturns:
Name Type Descriptionbytes 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.
NotesGuarantees:
- 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 Defaultcollection_name str Name of the MongoDB collection.
requiredmodel type[T] The Pydantic model class.
requiredcache_backend CacheBackend Backend used to store and fetch entries.
requiredconfig 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 Defaultfilter Optional[Dict[str, Any]] MongoDB filter dictionary.
None Returns:
Name Type Descriptionint int The number of matching documents.
"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.create","title":"createasync","text":"create(data: T) -> T\n Insert a document and cache the raw snapshot.
Parameters:
Name Type Description Defaultdata T The model instance to insert.
requiredReturns:
Name Type DescriptionT T The created model instance, including its ID.
"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.delete","title":"deleteasync","text":"delete(id: str | ObjectId) -> bool\n Delete a document and remove its cache entry.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID.
requiredReturns:
Name Type Descriptionbool bool True if a document was deleted, False otherwise.
"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.get_by_id","title":"get_by_idasync","text":"get_by_id(id: str | ObjectId) -> T | None\n Fetch a document, reading through the cache when enabled.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID.
requiredReturns:
Type DescriptionT | None Optional[T]: The model instance, or None when not found.
"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.get_many","title":"get_manyasync","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 Defaultfilter 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 Descriptionlist[T] List[T]: A list of Pydantic model instances.
Exampleusers = 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 Defaultid Union[str, ObjectId] The document ID to invalidate.
required"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.patch","title":"patchasync","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 Defaultid Union[str, ObjectId] The document ID (string or ObjectId).
requireddata Dict[str, Any] A partial dictionary of fields and values to update.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated Pydantic model instance if found, else None.
"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.update","title":"updateasync","text":"update(id: str | ObjectId, data: dict) -> T | None\n Update a document and refresh its cache entry.
Parameters:
Name Type Description Defaultid Union[str, ObjectId] The document ID.
requireddata dict Fields to set via $set.
requiredReturns:
Type DescriptionT | None Optional[T]: The updated model instance, or None when not found.
"},{"location":"cache/repository/#mongo_ops.cache.repository.CachedBaseRepository.warm_cache","title":"warm_cacheasync","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 Defaultids list[Union[str, ObjectId]] Document IDs to warm.
requiredReturns:
Name Type Descriptionint 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":"PopulateRuledataclass","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 Descriptionfield_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.
NotesGuarantees:
- 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 Defaultrepos dict[str, Any] Mapping of collection name to repository, used to fetch referenced documents.
requiredglobal_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 Defaultdocument T The document to depopulate in place.
requiredrules list[PopulateRule] Rules describing which fields to collapse.
requiredReturns:
Name Type DescriptionT T The depopulated document.
Raises:
Type DescriptionAttributeError If a list entry is not a BaseDocument where expected.
"},{"location":"populate/#mongo_ops.populate.PopulationEngine.populate","title":"populateasync","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 Defaultdocument T The document to populate in place.
requiredrules list[PopulateRule] Rules describing which fields to resolve and how deep.
requireddepth 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 DescriptionT T The populated document.
Raises:
Type DescriptionCircularReferenceError 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 Defaultcollection_name str Collection the repository manages.
requiredrepo 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.
NotesGuarantees:
- 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 Defaultrepos dict[str, Any] Mapping of collection name to repository, used to fetch referenced documents.
requiredglobal_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 Defaultdocument T The document to depopulate in place.
requiredrules list[PopulateRule] Rules describing which fields to collapse.
requiredReturns:
Name Type DescriptionT T The depopulated document.
Raises:
Type DescriptionAttributeError If a list entry is not a BaseDocument where expected.
"},{"location":"populate/engine/#mongo_ops.populate.engine.PopulationEngine.populate","title":"populateasync","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 Defaultdocument T The document to populate in place.
requiredrules list[PopulateRule] Rules describing which fields to resolve and how deep.
requireddepth 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 DescriptionT T The populated document.
Raises:
Type DescriptionCircularReferenceError 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 Defaultcollection_name str Collection the repository manages.
requiredrepo 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":"PopulateRuledataclass","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 Descriptionfield_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.
"}]}