Skip to content

Commit 5ca07f1

Browse files
WaVEVtimgraham
authored andcommitted
fix overlap lookup in subqueries
fixes #209
1 parent e2aaadb commit 5ca07f1

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

django_mongodb_backend/expressions.py

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,11 +119,10 @@ def query(self, compiler, connection, lookup_name=None):
119119
for col, i in subquery_compiler.column_indices.items()
120120
},
121121
}
122+
wrapping_result_pipeline = None
122123
# The result must be a list of values. The output is compressed with an
123124
# aggregation pipeline.
124125
if lookup_name in ("in", "range"):
125-
if subquery.aggregation_pipeline is None:
126-
subquery.aggregation_pipeline = []
127126
wrapping_result_pipeline = [
128127
{
129128
"$facet": {
@@ -155,12 +154,49 @@ def query(self, compiler, connection, lookup_name=None):
155154
}
156155
},
157156
]
157+
if lookup_name == "overlap":
158+
wrapping_result_pipeline = [
159+
{
160+
"$facet": {
161+
"group": [
162+
{"$project": {"tmp_name": expr.as_mql(subquery_compiler, connection)}},
163+
{
164+
"$unwind": "$tmp_name",
165+
},
166+
{
167+
"$group": {
168+
"_id": None,
169+
"tmp_name": {"$addToSet": "$tmp_name"},
170+
}
171+
},
172+
]
173+
}
174+
},
175+
{
176+
"$project": {
177+
field_name: {
178+
"$ifNull": [
179+
{
180+
"$getField": {
181+
"input": {"$arrayElemAt": ["$group", 0]},
182+
"field": "tmp_name",
183+
}
184+
},
185+
[],
186+
]
187+
}
188+
}
189+
},
190+
]
191+
if wrapping_result_pipeline:
158192
# If the subquery is a combinator, wrap the result at the end of the
159193
# combinator pipeline...
160194
if subquery.query.combinator:
161195
subquery.combinator_pipeline.extend(wrapping_result_pipeline)
162196
# ... otherwise put at the end of subquery's pipeline.
163197
else:
198+
if subquery.aggregation_pipeline is None:
199+
subquery.aggregation_pipeline = []
164200
subquery.aggregation_pipeline.extend(wrapping_result_pipeline)
165201
# Erase project_fields since the required value is projected above.
166202
subquery.project_fields = None

django_mongodb_backend/features.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):
8080
"auth_tests.test_views.LoginTest.test_login_session_without_hash_session_key",
8181
# GenericRelation.value_to_string() assumes integer pk.
8282
"contenttypes_tests.test_fields.GenericRelationTests.test_value_to_string",
83-
# overlap with values() returns no results:
84-
# https://github.com/mongodb-labs/django-mongodb/issues/209
85-
"model_fields_.test_arrayfield.QueryingTests.test_overlap_values",
8683
# icontains doesn't work on ArrayField:
8784
# Unsupported conversion from array to string in $convert
8885
"model_fields_.test_arrayfield.QueryingTests.test_icontains",

0 commit comments

Comments
 (0)