@@ -150,44 +150,27 @@ def get_subquery_wrapping_pipeline(self, compiler, connection, field_name, expr)
150150 # structure of EmbeddedModelArrayField on the RHS behaves similar to
151151 # ArrayField.
152152 return [
153+ {"$project" : {"tmp_name" : expr .as_mql (compiler , connection , as_expr = True )}},
154+ # To concatenate all the values from the RHS subquery,
155+ # use an $unwind followed by a $group.
153156 {
154- "$facet" : {
155- "gathered_data" : [
156- {"$project" : {"tmp_name" : expr .as_mql (compiler , connection , as_expr = True )}},
157- # To concatenate all the values from the RHS subquery,
158- # use an $unwind followed by a $group.
159- {
160- "$unwind" : "$tmp_name" ,
161- },
162- # The $group stage collects values into an array using
163- # $addToSet. The use of {_id: null} results in a
164- # single grouped array. However, because arrays from
165- # multiple documents are aggregated, the result is a
166- # list of lists.
167- {
168- "$group" : {
169- "_id" : None ,
170- "tmp_name" : {"$addToSet" : "$tmp_name" },
171- }
172- },
173- ]
174- }
157+ "$unwind" : "$tmp_name" ,
175158 },
159+ # The $group stage collects values into an array using
160+ # $addToSet. The use of {_id: null} results in a
161+ # single grouped array. However, because arrays from
162+ # multiple documents are aggregated, the result is a
163+ # list of lists.
176164 {
177- "$project" : {
178- field_name : {
179- "$ifNull" : [
180- {
181- "$getField" : {
182- "input" : {"$arrayElemAt" : ["$gathered_data" , 0 ]},
183- "field" : "tmp_name" ,
184- }
185- },
186- [],
187- ]
188- }
165+ "$group" : {
166+ "_id" : None ,
167+ "tmp_name" : {"$addToSet" : "$tmp_name" },
189168 }
190169 },
170+ # Add a dummy document in case of empty result.
171+ {"$unionWith" : {"pipeline" : [{"$documents" : [{"tmp_name" : []}]}]}},
172+ {"$limit" : 1 },
173+ {"$project" : {field_name : "$tmp_name" }},
191174 ]
192175
193176
0 commit comments