@@ -277,7 +277,9 @@ def execute_sql(
277277 try :
278278 query = self .build_query (
279279 # Avoid $project (columns=None) if unneeded.
280- columns if self .query .annotations or not self .query .default_cols else None
280+ columns
281+ if self .query .annotations or not self .query .default_cols or self .query .distinct
282+ else None
281283 )
282284 except EmptyResultSet :
283285 return iter ([]) if result_type == MULTI else None
@@ -378,7 +380,7 @@ def check_query(self):
378380 raise NotSupportedError ("QuerySet.datetimes() is not supported on MongoDB." )
379381 if "datefield" in self .query .annotations :
380382 raise NotSupportedError ("QuerySet.dates() is not supported on MongoDB." )
381- raise NotSupportedError ("QuerySet.distinct() is not supported on MongoDB." )
383+ # raise NotSupportedError("QuerySet.distinct() is not supported on MongoDB.")
382384 if self .query .extra :
383385 if any (key .startswith ("_prefetch_related_" ) for key in self .query .extra ):
384386 raise NotSupportedError ("QuerySet.prefetch_related() is not supported on MongoDB." )
@@ -397,6 +399,20 @@ def build_query(self, columns=None):
397399 )
398400 query .combinator_pipeline = self .get_combinator_queries ()
399401 else :
402+ # If we query distinct
403+ if self .query .distinct :
404+ distinct_fields = self .get_project_fields (columns , force_expression = True )
405+ if not query .aggregation_pipeline :
406+ query .aggregation_pipeline = []
407+ query .aggregation_pipeline .extend (
408+ [
409+ {"$group" : {"_id" : distinct_fields }},
410+ {"$addFields" : {key : f"$_id.{ key } " for key in distinct_fields }},
411+ ]
412+ )
413+ if "_id" not in distinct_fields :
414+ query .aggregation_pipeline .append ({"$unset" : "_id" })
415+
400416 query .project_fields = self .get_project_fields (columns , ordering_fields )
401417 # If columns is None, then get_project_fields() won't add
402418 # ordering_fields to $project. Use $addFields (extra_fields) instead.
@@ -767,7 +783,7 @@ def build_query(self, columns=None):
767783 # Avoid $project (columns=None) if unneeded.
768784 columns = (
769785 compiler .get_columns ()
770- if compiler .query .annotations or not compiler .query .default_cols
786+ if self .query .annotations or not self .query .default_cols or self . query . distinct
771787 else None
772788 )
773789 subquery = compiler .build_query (columns )
0 commit comments