Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions django_mongodb_backend/aggregates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]}
Expand Down
18 changes: 4 additions & 14 deletions django_mongodb_backend/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add link to the SERVER ticket and add an explanatory comment about the purpose of the $unionWith clause.

I think we can also mention it in the release notes as a performance improvement since the team said $facet prevents the use of optimizations.

pipeline.append({"$set": {"__now": "$$NOW"}})
pipeline.append({"$unionWith": {"pipeline": [{"$documents": [{}]}]}})
else:
group["_id"] = ids
pipeline.append({"$group": group})
Expand Down