diff --git a/django_mongodb_backend/aggregates.py b/django_mongodb_backend/aggregates.py index fb41ce4fc..9921e34ab 100644 --- a/django_mongodb_backend/aggregates.py +++ b/django_mongodb_backend/aggregates.py @@ -52,6 +52,7 @@ def count(self, compiler, connection, resolve_inner_expression=False): # If distinct=True or resolve_inner_expression=False, sum the size of the # set. lhs_mql = process_lhs(self, compiler, connection, as_expr=True) + lhs_mql = {"$ifNull": [lhs_mql, []]} # None shouldn't be counted, so subtract 1 if it's present. exits_null = {"$cond": {"if": {"$in": [{"$literal": None}, lhs_mql]}, "then": -1, "else": 0}} return {"$add": [{"$size": lhs_mql}, exits_null]} diff --git a/django_mongodb_backend/compiler.py b/django_mongodb_backend/compiler.py index cb867221e..6feb7b13e 100644 --- a/django_mongodb_backend/compiler.py +++ b/django_mongodb_backend/compiler.py @@ -235,20 +235,10 @@ def _build_aggregation_pipeline(self, ids, group): pipeline = [] if not ids: group["_id"] = None - pipeline.append({"$facet": {"group": [{"$group": group}]}}) - pipeline.append( - { - "$addFields": { - key: { - "$getField": { - "input": {"$arrayElemAt": ["$group", 0]}, - "field": key, - } - } - for key in group - } - } - ) + pipeline.append({"$group": group}) + # It may be a bug, $$NOW has to be called to be reachable in the rest of the pipeline. + pipeline.append({"$set": {"__now": "$$NOW"}}) + pipeline.append({"$unionWith": {"pipeline": [{"$documents": [{}]}]}}) else: group["_id"] = ids pipeline.append({"$group": group})