Skip to content

Unrecognized expression '$dateSubtract' #910

Open

Activity

  1. mbyrne00 commented on Nov 21, 2024

    @mbyrne00
    Author

    In case anyone else needs to patch their local working version while waiting for updates, here's how to do it ....

    Create a file mongomock_patch.py for example and here's my simple implementation of $dateSubtract without worrying about supporting timezone for now ....

    # custom_mongomock_patch.py
    from datetime import datetime, timedelta
    from unittest.mock import patch
    
    from dateutil.relativedelta import relativedelta
    from mongomock import aggregate
    
    
    # noinspection PyProtectedMember
    class _CustomParser(aggregate._Parser):
        def _handle_arithmetic_operator(self, operator, values):
            print(f"Custom handling of operator {operator} with values {values}")
            if operator == "$dateSubtract":
                if not isinstance(values, dict):
                    raise ValueError(f"Expected dict for $dateSubtract, got {values}")
                start_date = self.parse(values.get("startDate"))
                unit = values.get("unit")
                amount = self.parse(values.get("amount"))
    
                start_date = datetime.fromisoformat(start_date) if isinstance(start_date, str) else start_date
                if not isinstance(start_date, datetime):
                    raise ValueError(f"Expected datetime or iso string for startDate, got {start_date}")
    
                return start_date - _to_delta(unit, amount)
    
            return super()._handle_arithmetic_operator(operator, values)
    
    
    def patch_mongomock_aggregation():
        aggregate.arithmetic_operators.update(["$dateSubtract"])
        return patch("mongomock.aggregate._Parser", _CustomParser)
    
    
    def _to_delta(unit: str, amount: any):
        if unit == "year":
            return relativedelta(years=amount)
        elif unit == "quarter":
            return relativedelta(months=3 * amount)
        elif unit == "month":
            return relativedelta(months=amount)
        elif unit == "week":
            return timedelta(weeks=amount)
        elif unit == "day":
            return timedelta(days=amount)
        elif unit == "hour":
            return timedelta(hours=amount)
        elif unit == "minute":
            return timedelta(minutes=amount)
        elif unit == "second":
            return timedelta(seconds=amount)
        elif unit == "millisecond":
            return timedelta(milliseconds=amount)
        else:
            raise ValueError(f"Unsupported unit: {unit}")

    Then in your test or your conftest.py just do the following (import patch_mongomock_aggregation() from your file above, wherever that may be ... sample imports below

    import pytest
    from mongomock_patch import patch_mongomock_aggregation
    
    @pytest.fixture(autouse=True)
    def patch_aggregation():
        with patch_mongomock_aggregation():
            yield
  2. added 2 commits that reference this issue on Nov 22, 2026
    0ccf936
    b838ed0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions