Skip to content

Commit 5e96cb5

Browse files
committed
Comments and docstring
1 parent 4dea72d commit 5e96cb5

File tree

2 files changed

+6
-0
lines changed

2 files changed

+6
-0
lines changed

django_mongodb_backend/compiler.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ def __init__(self, *args, **kwargs):
3838
self.subqueries = []
3939
# Atlas search stage.
4040
self.search_pipeline = []
41+
# The aggregation has no group-by fields and needs wrapping.
4142
self.wrap_for_global_aggregation = False
4243

4344
def _get_group_alias_column(self, expr, annotation_group_idx):
@@ -236,6 +237,7 @@ def _build_aggregation_pipeline(self, ids, group):
236237
pipeline = []
237238
if not ids:
238239
pipeline.append({"$group": {"_id": None, **group}})
240+
# If ids is empty, a global group-by is applied
239241
self.wrap_for_global_aggregation = True
240242
else:
241243
group["_id"] = ids

django_mongodb_backend/query.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,15 +93,19 @@ 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
9697
pipeline = [
9798
{"$collStats": {}},
99+
# Wrap the actual aggregation inside a lookup so its result
100+
# always appears as a one document array
98101
{
99102
"$lookup": {
100103
"from": self.compiler.collection_name,
101104
"as": "__wrapped",
102105
"pipeline": pipeline,
103106
}
104107
},
108+
# Use {} If the inner aggregation returns nothing, otherwise unwrap
105109
{
106110
"$replaceWith": {
107111
"$cond": [{"$eq": ["$__wrapped", []]}, {}, {"$first": "$__wrapped"}]

0 commit comments

Comments
 (0)