@@ -53,7 +53,10 @@ def case(self, compiler, connection):
53
53
def col (self , compiler , connection ): # noqa: ARG001
54
54
# If it is a subquery and the columns belongs to one of the ancestors,
55
55
# the column shall be stored to be passed using $let in a $lookup stage.
56
- if self .alias in compiler .parent_collections :
56
+ if (
57
+ self .alias not in compiler .query .alias_refcount
58
+ or compiler .query .alias_refcount [self .alias ] == 0
59
+ ):
57
60
try :
58
61
index = compiler .column_mapping [self ]
59
62
except KeyError :
@@ -89,10 +92,9 @@ def order_by(self, compiler, connection):
89
92
return self .expression .as_mql (compiler , connection )
90
93
91
94
92
- def query (self , compiler , connection ):
95
+ def query (self , compiler , connection , lookup_name = None ):
93
96
subquery_compiler = self .get_compiler (connection = connection )
94
97
subquery_compiler .pre_sql_setup (with_col_aliases = False )
95
- subquery_compiler .parent_collections = {compiler .collection_name } | compiler .parent_collections
96
98
columns = subquery_compiler .get_columns ()
97
99
field_name , expr = columns [0 ]
98
100
subquery = subquery_compiler .build_query (
@@ -112,8 +114,8 @@ def query(self, compiler, connection):
112
114
for col , i in subquery_compiler .column_mapping .items ()
113
115
},
114
116
}
115
- # the result must be a list of values. Se we compress the output with an aggregation pipeline.
116
- if not self . has_limit_one ( ):
117
+ # The result must be a list of values. Se we compress the output with an aggregation pipeline.
118
+ if lookup_name in ( "in" , "range" ):
117
119
subquery .aggregation_pipeline = [
118
120
{
119
121
"$group" : {
@@ -144,8 +146,8 @@ def star(self, compiler, connection): # noqa: ARG001
144
146
return {"$literal" : True }
145
147
146
148
147
- def subquery (self , compiler , connection ):
148
- return self .query .as_mql (compiler , connection )
149
+ def subquery (self , compiler , connection , lookup_name = None ):
150
+ return self .query .as_mql (compiler , connection , lookup_name = lookup_name )
149
151
150
152
151
153
def exists (self , compiler , connection ):
0 commit comments