Skip to content

Commit 09083d3

Browse files
committed
Fix pipeline position of unionWith.
1 parent 3014ef6 commit 09083d3

File tree

2 files changed

+6
-1
lines changed

2 files changed

+6
-1
lines changed

django_mongodb_backend/compiler.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ def __init__(self, *args, **kwargs):
4040
self.search_pipeline = []
4141
# The aggregation has no group-by fields and needs wrapping.
4242
self.wrap_for_global_aggregation = False
43+
# HAVING stage match (MongoDB equivalent)
44+
self.having_match_mql = None
4345

4446
def _get_group_alias_column(self, expr, annotation_group_idx):
4547
"""Generate a dummy field for use in the ids fields in $group."""
@@ -324,7 +326,7 @@ def pre_sql_setup(self, with_col_aliases=False):
324326
pipeline.extend(query.get_pipeline())
325327
# Remove the added subqueries.
326328
self.subqueries = []
327-
pipeline.append({"$match": having})
329+
self.having_match_mql = having
328330
self.aggregation_pipeline = pipeline
329331
self.annotations = {
330332
target: expr.replace_expressions(all_replacements)

django_mongodb_backend/query.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ def __init__(self, compiler):
5050
self.lookup_pipeline = None
5151
self.project_fields = None
5252
self.aggregation_pipeline = compiler.aggregation_pipeline
53+
self.having = compiler.having_match_mql
5354
self.search_pipeline = compiler.search_pipeline
5455
self.extra_fields = None
5556
self.combinator_pipeline = None
@@ -95,6 +96,8 @@ def get_pipeline(self):
9596
if self.wrap_for_global_aggregation:
9697
# Add an empty extra document to handle default values on empty results
9798
pipeline.append({"$unionWith": {"pipeline": [{"$documents": [{}]}]}})
99+
if self.having:
100+
pipeline.append({"$match": self.having})
98101
if self.project_fields:
99102
pipeline.append({"$project": self.project_fields})
100103
if self.combinator_pipeline:

0 commit comments

Comments
 (0)