Skip to content

Commit 3014ef6

Browse files
committed
Replace collstats to handle empty results in global aggregations
1 parent 5e96cb5 commit 3014ef6

File tree

1 file changed

+2
-19
lines changed

1 file changed

+2
-19
lines changed

django_mongodb_backend/query.py

Lines changed: 2 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -93,25 +93,8 @@ def get_pipeline(self):
9393
if self.aggregation_pipeline:
9494
pipeline.extend(self.aggregation_pipeline)
9595
if self.wrap_for_global_aggregation:
96-
# Use $collStats as a pivot to guarantee a single input document
97-
pipeline = [
98-
{"$collStats": {}},
99-
# Wrap the actual aggregation inside a lookup so its result
100-
# always appears as a one document array
101-
{
102-
"$lookup": {
103-
"from": self.compiler.collection_name,
104-
"as": "__wrapped",
105-
"pipeline": pipeline,
106-
}
107-
},
108-
# Use {} If the inner aggregation returns nothing, otherwise unwrap
109-
{
110-
"$replaceWith": {
111-
"$cond": [{"$eq": ["$__wrapped", []]}, {}, {"$first": "$__wrapped"}]
112-
}
113-
},
114-
]
96+
# Add an empty extra document to handle default values on empty results
97+
pipeline.append({"$unionWith": {"pipeline": [{"$documents": [{}]}]}})
11598
if self.project_fields:
11699
pipeline.append({"$project": self.project_fields})
117100
if self.combinator_pipeline:

0 commit comments

Comments
 (0)