Skip to content

Commit 23f4792

Browse files
committed
Remove $facet in top level group stages
1 parent f8ba881 commit 23f4792

File tree

2 files changed

+5
-14
lines changed

2 files changed

+5
-14
lines changed

django_mongodb_backend/aggregates.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ def count(self, compiler, connection, resolve_inner_expression=False):
5252
# If distinct=True or resolve_inner_expression=False, sum the size of the
5353
# set.
5454
lhs_mql = process_lhs(self, compiler, connection, as_expr=True)
55+
lhs_mql = {"$ifNull": [lhs_mql, []]}
5556
# None shouldn't be counted, so subtract 1 if it's present.
5657
exits_null = {"$cond": {"if": {"$in": [{"$literal": None}, lhs_mql]}, "then": -1, "else": 0}}
5758
return {"$add": [{"$size": lhs_mql}, exits_null]}

django_mongodb_backend/compiler.py

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -235,20 +235,10 @@ def _build_aggregation_pipeline(self, ids, group):
235235
pipeline = []
236236
if not ids:
237237
group["_id"] = None
238-
pipeline.append({"$facet": {"group": [{"$group": group}]}})
239-
pipeline.append(
240-
{
241-
"$addFields": {
242-
key: {
243-
"$getField": {
244-
"input": {"$arrayElemAt": ["$group", 0]},
245-
"field": key,
246-
}
247-
}
248-
for key in group
249-
}
250-
}
251-
)
238+
pipeline.append({"$group": group})
239+
# It may be a bug, $$NOW has to be called to be reachable in the rest of the pipeline.
240+
pipeline.append({"$set": {"__now": "$$NOW"}})
241+
pipeline.append({"$unionWith": {"pipeline": [{"$documents": [{}]}]}})
252242
else:
253243
group["_id"] = ids
254244
pipeline.append({"$group": group})

0 commit comments

Comments
 (0)