Skip to content

Repository

mongo_ops.cache.repository

Summary

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

Classes

CachedBaseRepository

1
2
3
4
5
6
CachedBaseRepository(
    collection_name: str,
    model: type[T],
    cache_backend: CacheBackend,
    config: CacheConfig | None = None,
)

Bases: BaseRepository[T], Generic[T]

Repository that reads and writes through a cache backend.

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

Notes

Guarantees:

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

Initialize the cached repository.

Parameters:

Name Type Description Default
collection_name str

Name of the MongoDB collection.

required
model type[T]

The Pydantic model class.

required
cache_backend CacheBackend

Backend used to store and fetch entries.

required
config Optional[CacheConfig]

Cache configuration; a default CacheConfig is used when None.

None
Functions
count async
count(filter: dict[str, Any] | None = None) -> int

Count documents matching a filter.

Parameters:

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

MongoDB filter dictionary.

None

Returns:

Name Type Description
int int

The number of matching documents.

create async
create(data: T) -> T

Insert a document and cache the raw snapshot.

Parameters:

Name Type Description Default
data T

The model instance to insert.

required

Returns:

Name Type Description
T T

The created model instance, including its ID.

delete async
delete(id: str | ObjectId) -> bool

Delete a document and remove its cache entry.

Parameters:

Name Type Description Default
id Union[str, ObjectId]

The document ID.

required

Returns:

Name Type Description
bool bool

True if a document was deleted, False otherwise.

get_by_id async
get_by_id(id: str | ObjectId) -> T | None

Fetch a document, reading through the cache when enabled.

Parameters:

Name Type Description Default
id Union[str, ObjectId]

The document ID.

required

Returns:

Type Description
T | None

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

get_many async
1
2
3
4
5
6
get_many(
    filter: dict[str, Any] | None = None,
    skip: int = 0,
    limit: int = 100,
    sort: list[tuple] | None = None,
) -> list[T]

Retrieve multiple documents with filtering, pagination, and sorting.

Parameters:

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

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

None
skip int

Number of documents to skip for pagination.

0
limit int

Maximum number of documents to return (default 100).

100
sort Optional[List[tuple]]

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

None

Returns:

Type Description
list[T]

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

Example
1
2
3
4
5
users = await repo.get_many(
    filter={"role": "admin"},
    limit=10,
    sort=[("username", 1)]
)
invalidate_cache async
invalidate_cache(id: str | ObjectId) -> None

Remove a single document's cache entry.

Parameters:

Name Type Description Default
id Union[str, ObjectId]

The document ID to invalidate.

required
patch async
patch(id: str | ObjectId, data: dict[str, Any]) -> T | None

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

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

Parameters:

Name Type Description Default
id Union[str, ObjectId]

The document ID (string or ObjectId).

required
data Dict[str, Any]

A partial dictionary of fields and values to update.

required

Returns:

Type Description
T | None

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

update async
update(id: str | ObjectId, data: dict) -> T | None

Update a document and refresh its cache entry.

Parameters:

Name Type Description Default
id Union[str, ObjectId]

The document ID.

required
data dict

Fields to set via $set.

required

Returns:

Type Description
T | None

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

warm_cache async
warm_cache(ids: list[str | ObjectId]) -> int

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

Docs already present in the cache are skipped.

Parameters:

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

Document IDs to warm.

required

Returns:

Name Type Description
int int

Number of entries added to the cache.

Functions