Skip to content

Commit

Permalink
Merge pull request #53 from mohamadkhalaj/main
Browse files Browse the repository at this point in the history
Support multi expression in group
  • Loading branch information
seyed-dev authored Nov 12, 2023
2 parents 7cc267a + 7595b07 commit 81ef660
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
13 changes: 10 additions & 3 deletions aggify/aggify.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,13 @@ def project(self, **kwargs: QueryParams) -> "Aggify":
return self

@last_out_stage_check
def group(self, expression: Union[str, None] = "id") -> "Aggify":
if expression:
def group(self, expression: Union[str, Dict, List, None] = "id") -> "Aggify":
if isinstance(expression, list):
expression = {
field: f"${self.get_field_name_recursively(field)}"
for field in expression
}
if expression and not isinstance(expression, dict):
try:
expression = "$" + self.get_field_name_recursively(expression)
except InvalidField:
Expand Down Expand Up @@ -454,7 +459,9 @@ def annotate(

# Determine the data type based on the aggregation operator
self.pipelines[-1]["$group"].update({annotate_name: {acc: value}})
self.base_model._fields[annotate_name] = field_type # noqa
base_model_fields = self.base_model._fields # noqa
if not base_model_fields.get(annotate_name, None):
base_model_fields[annotate_name] = field_type
return self

def __match(self, matches: Dict[str, Any]):
Expand Down
4 changes: 4 additions & 0 deletions tests/test_aggify.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,3 +662,7 @@ def test_lookup_raw_let(self):
"as": "test_name",
}
assert "test_name" in list(aggify.base_model._fields.keys())

def test_group_multi_expressions(self):
thing = list(Aggify(BaseModel).group(["name", "age"]))
assert thing[0]["$group"] == {"_id": {"name": "$name", "age": "$age"}}

0 comments on commit 81ef660

Please sign in to comment.