Skip to content

General

General purpose query methods.

GeneralMixin

General purpose query methods.

Source code in src/ramifice/commons/general.py
class GeneralMixin:
    """General purpose query methods."""

    @classmethod
    def from_mongo_doc(
        cls,
        mongo_doc: dict[str, Any],
        lang_code: str = deepcopy(Translator.DEFAULT_LOCALE),
    ) -> Any:
        """Create a Model instance from a Mongo document."""
        # pyrefly: ignore [bad-argument-count]
        instance: Any = cls(lang_code)

        for mongo_key, mongo_value in mongo_doc.items():
            if mongo_value is None:
                continue

            f_name = mongo_key if mongo_key != "_id" else "id"
            f__core = getattr(instance, f"{f_name}__core")
            f_type = f__core.field_type
            f_value = None

            if f_type == "TextField":
                f_value = mongo_value.get(lang_code, "- -") if isinstance(mongo_value, dict) else mongo_value
            elif f_type == "DateField":
                f_value = mongo_value.date()
            elif f_type == "PasswordField":
                f_value = None
            else:
                f_value = mongo_value

            setattr(instance, f_name, f_value)

        return instance

    @classmethod
    async def estimated_document_count(  # type: ignore[no-untyped-def]
        cls,
        comment: Any | None = None,
        **kwargs,
    ) -> int:
        """Get an estimate of the number of documents in this collection using collection metadata."""
        metadata = cls.META
        # Get collection for current model.
        collection: AsyncCollection = Config.MONGO_DATABASE[metadata["collection_name"]]

        return await collection.estimated_document_count(
            comment=comment,
            **kwargs,
        )

    @classmethod
    async def count_documents(  # type: ignore[no-untyped-def]
        cls,
        filter: Any,
        session: Any | None = None,
        comment: Any | None = None,
        lang_code: str = deepcopy(Translator.DEFAULT_LOCALE),
        **kwargs,
    ) -> int:
        """Count the number of documents in this collection."""
        metadata = cls.META
        # Get collection for current model.
        collection: AsyncCollection = Config.MONGO_DATABASE[metadata["collection_name"]]
        # Correcting filter.
        if filter is not None:
            filter = correct_mongo_filter(cls, filter, lang_code)

        return await collection.count_documents(
            filter=filter,
            session=session,
            comment=comment,
            **kwargs,
        )

    @classmethod
    async def aggregate(  # type: ignore[no-untyped-def]
        cls,
        pipeline: Any,
        session: Any | None = None,
        let: Any | None = None,
        comment: Any | None = None,
        lang_code: str = deepcopy(Translator.DEFAULT_LOCALE),
        **kwargs,
    ) -> AsyncCommandCursor:
        """Perform an aggregation using the aggregation framework on this collection."""
        metadata = cls.META
        # Get collection for current model.
        collection: AsyncCollection = Config.MONGO_DATABASE[metadata["collection_name"]]
        # Correcting filter.
        if pipeline is not None:
            pipeline = correct_mongo_filter(cls, pipeline, lang_code)

        return await collection.aggregate(
            pipeline=pipeline,
            session=session,
            let=let,
            comment=comment,
            **kwargs,
        )

    @classmethod
    async def distinct(  # type: ignore[no-untyped-def]
        cls,
        key: Any,
        filter: Any | None = None,
        session: Any | None = None,
        comment: Any | None = None,
        hint: Any | None = None,
        lang_code: str = deepcopy(Translator.DEFAULT_LOCALE),
        **kwargs,
    ) -> list[Any]:
        """Get a list of distinct values for key among all documents in this collection.

        Returns an array of unique values for specified field of collection.
        """
        metadata = cls.META
        # Get collection for current model.
        collection: AsyncCollection = Config.MONGO_DATABASE[metadata["collection_name"]]
        # Correcting filter.
        if filter is not None:
            filter = correct_mongo_filter(cls, filter, lang_code)

        return await collection.distinct(
            key=key,
            filter=filter,
            session=session,
            comment=comment,
            hint=hint,
            **kwargs,
        )

aggregate(pipeline, session=None, let=None, comment=None, lang_code=deepcopy(Translator.DEFAULT_LOCALE), **kwargs) async classmethod

Perform an aggregation using the aggregation framework on this collection.

Source code in src/ramifice/commons/general.py
@classmethod
async def aggregate(  # type: ignore[no-untyped-def]
    cls,
    pipeline: Any,
    session: Any | None = None,
    let: Any | None = None,
    comment: Any | None = None,
    lang_code: str = deepcopy(Translator.DEFAULT_LOCALE),
    **kwargs,
) -> AsyncCommandCursor:
    """Perform an aggregation using the aggregation framework on this collection."""
    metadata = cls.META
    # Get collection for current model.
    collection: AsyncCollection = Config.MONGO_DATABASE[metadata["collection_name"]]
    # Correcting filter.
    if pipeline is not None:
        pipeline = correct_mongo_filter(cls, pipeline, lang_code)

    return await collection.aggregate(
        pipeline=pipeline,
        session=session,
        let=let,
        comment=comment,
        **kwargs,
    )

count_documents(filter, session=None, comment=None, lang_code=deepcopy(Translator.DEFAULT_LOCALE), **kwargs) async classmethod

Count the number of documents in this collection.

Source code in src/ramifice/commons/general.py
@classmethod
async def count_documents(  # type: ignore[no-untyped-def]
    cls,
    filter: Any,
    session: Any | None = None,
    comment: Any | None = None,
    lang_code: str = deepcopy(Translator.DEFAULT_LOCALE),
    **kwargs,
) -> int:
    """Count the number of documents in this collection."""
    metadata = cls.META
    # Get collection for current model.
    collection: AsyncCollection = Config.MONGO_DATABASE[metadata["collection_name"]]
    # Correcting filter.
    if filter is not None:
        filter = correct_mongo_filter(cls, filter, lang_code)

    return await collection.count_documents(
        filter=filter,
        session=session,
        comment=comment,
        **kwargs,
    )

distinct(key, filter=None, session=None, comment=None, hint=None, lang_code=deepcopy(Translator.DEFAULT_LOCALE), **kwargs) async classmethod

Get a list of distinct values for key among all documents in this collection.

Returns an array of unique values for specified field of collection.

Source code in src/ramifice/commons/general.py
@classmethod
async def distinct(  # type: ignore[no-untyped-def]
    cls,
    key: Any,
    filter: Any | None = None,
    session: Any | None = None,
    comment: Any | None = None,
    hint: Any | None = None,
    lang_code: str = deepcopy(Translator.DEFAULT_LOCALE),
    **kwargs,
) -> list[Any]:
    """Get a list of distinct values for key among all documents in this collection.

    Returns an array of unique values for specified field of collection.
    """
    metadata = cls.META
    # Get collection for current model.
    collection: AsyncCollection = Config.MONGO_DATABASE[metadata["collection_name"]]
    # Correcting filter.
    if filter is not None:
        filter = correct_mongo_filter(cls, filter, lang_code)

    return await collection.distinct(
        key=key,
        filter=filter,
        session=session,
        comment=comment,
        hint=hint,
        **kwargs,
    )

estimated_document_count(comment=None, **kwargs) async classmethod

Get an estimate of the number of documents in this collection using collection metadata.

Source code in src/ramifice/commons/general.py
@classmethod
async def estimated_document_count(  # type: ignore[no-untyped-def]
    cls,
    comment: Any | None = None,
    **kwargs,
) -> int:
    """Get an estimate of the number of documents in this collection using collection metadata."""
    metadata = cls.META
    # Get collection for current model.
    collection: AsyncCollection = Config.MONGO_DATABASE[metadata["collection_name"]]

    return await collection.estimated_document_count(
        comment=comment,
        **kwargs,
    )

from_mongo_doc(mongo_doc, lang_code=deepcopy(Translator.DEFAULT_LOCALE)) classmethod

Create a Model instance from a Mongo document.

Source code in src/ramifice/commons/general.py
@classmethod
def from_mongo_doc(
    cls,
    mongo_doc: dict[str, Any],
    lang_code: str = deepcopy(Translator.DEFAULT_LOCALE),
) -> Any:
    """Create a Model instance from a Mongo document."""
    # pyrefly: ignore [bad-argument-count]
    instance: Any = cls(lang_code)

    for mongo_key, mongo_value in mongo_doc.items():
        if mongo_value is None:
            continue

        f_name = mongo_key if mongo_key != "_id" else "id"
        f__core = getattr(instance, f"{f_name}__core")
        f_type = f__core.field_type
        f_value = None

        if f_type == "TextField":
            f_value = mongo_value.get(lang_code, "- -") if isinstance(mongo_value, dict) else mongo_value
        elif f_type == "DateField":
            f_value = mongo_value.date()
        elif f_type == "PasswordField":
            f_value = None
        else:
            f_value = mongo_value

        setattr(instance, f_name, f_value)

    return instance