Repository navigation
fix(mongodb): a comparison against a subquery in a where query runs the subquery - #17161
borinquenkid wants to merge 22 commits into
Conversation
…he subquery
where { age > avg(age) } and the other aggregate subqueries returned no rows on MongoDB, because the subquery was compared as an object and
not run: != against an empty subquery returned every row, notIn threw 'Queries of type NotIn are not supported', and deleteAll removed
every row of a != query. MongoDB runs the subquery first now, as the other datastores do through a join, for ==, !=, >, >=, <, <= against
avg, max, min and sum and for inList and notIn, in association blocks and for get(), and deleteAll and updateAll select the rows a list does.
A comparison against a subquery that returns more than one row, and the exists, notExists, all and some forms, throw an
InvalidDataAccessResourceUsageException. The MongoDB half of #16875 for the oldest branch that has the bug; Neo4j, which 7.0.x does not build, stays there.
Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…k stays at its level The filter of an embedded block was qualified by prefixing every top-level key with the property, so a negation, which is a top-level $nor, became address.$nor and matched nothing; the notIn of a subquery inside such a block returned no row. The logical operators are rewritten recursively instead and stay where they are, as on 8.0.x (385d246). Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A negated list inside an embedded block also matches an owner that has no embedded value.
| return membership(in.getProperty(), subqueryValues(in.getSubquery()), negated); | ||
| } | ||
| if (criterion instanceof NotIn notIn) { | ||
| Negation negation = new Negation(); |
There was a problem hiding this comment.
address { notIn('city', names) } should match only an owner whose city is not in that list. An owner with no address also matches. Require the address.
…mbedded value
MongoDB matches a missing field with $ne, $nin, $not and $nor, so address { notIn('city', names) }, address { ne('city', x) },
ne('address.city', x), not { eq('address.city', x) } and where { address.city != x } also matched an owner that has no address, which the
condition does not match on Hibernate, where the embedded value is the columns of its owner. A negation on a path through an embedded
property now also requires that value, at the level of the query document that holds it, so the branch of an or that holds the negation
is restricted and the owners that match another branch are not. CriteriaEmbeddedNegationSpec has the table for Hibernate 5 and MongoDB:
19 rows over the block, the dotted property, a detached criteria and a where query, ne, notIn and not, an or with and without an embedded
branch, an and, a negated block and a count; 15 fail on MongoDB without the change.
Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…the table covers the literal lists Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
@jamesfredley Fixed, and not only for I wrote the table first,
Not covered, with the reason: an owner that has the embedded value with the property itself unset still matches a negated condition on MongoDB (the same as a negated condition on a plain property there), which is a different change; the in-memory datastore does not answer criteria on an embedded value at all, so the spec runs for Hibernate 5 and MongoDB; |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A negation that mentions an embedded value also drops an owner that has no embedded value.
| for (Map.Entry<String, Object> entry : level.entrySet()) { | ||
| String key = entry.getKey(); | ||
| Object value = entry.getValue(); | ||
| if (NOR_OPERATOR.equals(key)) { |
There was a problem hiding this comment.
not { and { eq('name', 'Bob'); eq('address.city', 'Paris') } } should match Nina, who has no address, because her name is not Bob. She is left out, because this requires an address. Match her.
…ue of each condition and not of the whole group Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…st a reference evaluator A generated matrix of leaves, groups and negations over a name, an age and an embedded address, run through a criteria builder and a detached criteria on Hibernate 5 and MongoDB, and compared with SQL three-valued logic. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
Pushed 6e2cb3a. The embedded value was required for the whole negated group. A
Not covered here: a property that is there with a null value. MongoDB returns that owner for
For Hibernate 5 there is no documentation of the null case either; the value is the one the spec measures: Because this has come one shape at a time, the last commit adds |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A negated list inside a renamed embedded field still matches an owner that has no embedded value.
| StringBuilder path = new StringBuilder(); | ||
| String innermost = null; | ||
| for (int i = 0; i < parts.length - 1 && current != null; i++) { | ||
| PersistentProperty property = current.getPropertyByName(parts[i]); |
There was a problem hiding this comment.
address is stored as addr. address { notIn('city', names) } should match only an owner whose city is not in that list. An owner with no address also matches, because this looks up addr as a property and misses address. Require the address.
…ther names, at each level, requires the value Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
I could not reproduce this one, so there is no code change in this push, only rows (cb97fd7). The line you cite, The new spec, If the mapping you ran differs (for instance how |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A negated list inside a renamed embedded field still matches an owner that has no embedded value.
| StringBuilder path = new StringBuilder(); | ||
| String innermost = null; | ||
| for (int i = 0; i < parts.length - 1 && current != null; i++) { | ||
| PersistentProperty property = current.getPropertyByName(parts[i]); |
There was a problem hiding this comment.
address is stored as addr. address { notIn('city', names) } should match only an owner whose city is not in that list. An owner with no address also matches, because this looks up addr as a property and misses address. Require the address.
…alue stored under other names Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
Pushed d54286c, test rows only; I still cannot reproduce this one, so there is no code change, and I would like to see the query that fails. The lookup you cite, One thing about the form in your comment: If you ran it with a different mapping or a different call, please send the closure and the mapping and I will turn them into a row; a row that fails is a bug to fix here. |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A negated list inside a renamed embedded field still matches an owner that has no embedded value.
| } | ||
| return new LessThanEquals(property.getProperty(), value); | ||
| } | ||
| return criterion; |
There was a problem hiding this comment.
address is stored as addr. address { not { inList('city', names) } } should match only an owner whose city is not in that list. An owner with no address also matches, because this leaves the block as it is and does not require addr. Require the address.
There was a problem hiding this comment.
@jamesfredley I could not make an owner with no address match this query. With address stored as addr, address { not { inList('city', names) } } returns no owner at all, on 7.0.x without this change (7165c2d) and on f1326ee, with a literal list or a subquery, from a DetachedCriteria and from createCriteria().
The form that does return the owner with no address is not { address { inList('city', names) } } (I ran it with a literal list), also on both. This pull request leaves embedded blocks as they are. #17187 covers a negation of an embedded value in both positions, and #17189 holds the fix for it.
sbglasius
left a comment
There was a problem hiding this comment.
This is an AI assisted review
f1326ee addresses my earlier points: embedded blocks are now left as on 7.0.x, and where.adoc no longer mentions Neo4j.
@jamesfredley the address { not { inList(...) } } case in the new thread looks like the existing 7.0.x behaviour (#17187). This PR no longer touches association blocks, and the fix is in #17189. Could that thread move there?
The Windows build failure looks unrelated; a rerun should clear it.
Both sides added upgrade notes at one place; all are kept. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
7.0.x is merged into this branch (3ef2758) to resolve a conflict in the upgrade guide. Nothing else changed, and the tests and codeStyle pass on the merged tree. Approvals on the earlier commit need to be given again for the merge rule. |
jdaugherty
left a comment
There was a problem hiding this comment.
The original MongoDB aggregate-comparison example from #16809 now works, and the 23 AggregateSubquerySpec tests pass. Two incorrect-result cases remain in the new subquery resolver, both reproduced through public APIs for reads, updateAll, and deleteAll; details are inline.
Validation on JDK 17 and MongoDB 7.0.19: the existing spec and 23 additional focused cases passed (46 total). A separate targeted regression spec produced nine failing cases for the two findings and three passing controls for literal embedded-value comparisons. Full module suites were not run.
| private Collection<?> subqueryValues(QueryableCriteria<?> subquery) { | ||
| List<?> rows = subquery.list(); | ||
| // a store may return a list that loads its elements when it is first read: a copy has all of them | ||
| return rows == null ? Collections.emptyList() : new ArrayList<>(rows); |
There was a problem hiding this comment.
[P2] Preserve a null aggregate result before resolving membership
For records A(age:10), B(age:20), and Unknown(age:null), def average = Person.where { name == 'Unknown' }.avg('age') followed by new DetachedCriteria(Person).build { gt('age', 0); notIn('age', average) } returns A and B. The existing aggregate projection reader drops the null average and returns [], so this method passes an empty set to membership() instead of a null-valued aggregate result. Under the null-subquery semantics implemented here, neither non-null age should satisfy NOT IN (NULL). I reproduced the same result when the aggregate selects no records; updateAll updates both records and deleteAll deletes both instead of affecting zero. Preserve the aggregate's null-result distinction when resolving membership, and cover these bulk-operation cases. The outer gt('age', 0) excludes ordinary null/missing-field behavior from the reproducer.
There was a problem hiding this comment.
Fixed in a0f02c0. A subquery whose projections are only avg, max, min or sum always selects one row in SQL, and that row is null when no value is selected. The reader of an aggregate projection drops that null, so subqueryValues now returns one null for it. A negated membership against it is unknown for every row.
AggregateSubquerySpec has a new row for your reproducer (people with ages 10 and 20 and one without; gt('age', 0) and notIn('age', <average of the person without an age>)). It checks the read, updateAll and deleteAll. Before the change the read returned both people; now it returns none, updateAll changes 0 rows and deleteAll deletes 0. The full MongoDB core suite passes (594 tests).
| " rows, but a comparison needs exactly one value"); | ||
| } | ||
| // an entity is compared by its identifier, as it is when it is given as the value of the comparison | ||
| Object value = resolveIdIfEntity(rows.get(0)); |
There was a problem hiding this comment.
[P2] Keep embedded scalar results as embedded values
resolveIdIfEntity also converts an embedded @Entity to its identifier. With Source holding an embedded Address(postCode:'10000') and Missing having no address, def selected = new DetachedCriteria(Person).build { eq('name', 'Source') }.property('address') returns one Address whose ID is null. Using eq('address', selected) now turns that value into null and selects Missing instead of Source. I reproduced incorrect reads, updateAll updating Missing, and deleteAll deleting Missing; passing selected.list()[0] as the literal comparison value correctly selects Source in all three operations. This is a top-level scalar comparison. Preserve the embedded value using the property-aware conversion already used for literal comparisons, or reject an unsupported comparison before issuing the query, rather than converting it into equality with null.
There was a problem hiding this comment.
Fixed in a0f02c0. When the compared property is an embedded one, the value the subquery selected stays the embedded value and goes through the same conversion as a literal comparison. resolveIdIfEntity now applies only to the other properties, where the value stands for an entity by its identifier.
AggregateSubquerySpec has a new row with an embedded @Entity place: eq('place', <place of Source>) selects Source and not the holder without a place, in the read, updateAll and deleteAll. Before the change it selected the holder without a place.
…in a comparison with a subquery A subquery that selects the average, maximum, minimum or sum of no value is one null in SQL, so NOT IN against it matches no row; MongoQuery passed an empty list and matched every row. An embedded value selected by a subquery was converted to its null identifier, so the comparison selected the rows without it; it now stays the embedded value. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
jdaugherty
left a comment
There was a problem hiding this comment.
Thanks for a0f02c0. The two cases from my previous review now behave correctly: null-average membership affects no rows, and scalar embedded-value equality selects the holder of that value.
[P2] Embedded-value membership still selects and modifies the wrong records. The membership branches in MongoQuery.java:481–487 pass embedded entities into In, where BsonQuery.java:780–794 converts them to their null identifiers.
With a nullable embedded @Entity place, Source holds Place(postCode: '10000') and Missing has no place:
def selected = new DetachedCriteria(Holder).build {
eq('name', 'Source')
}.property('place')
def query = new DetachedCriteria(Holder).build {
inList('place', selected)
}query.list() returns Missing, and updateAll/deleteAll update/delete Missing instead of Source. Replacing inList with notIn returns and modifies Source, although that holder's place is exactly the selected value and must be excluded. Scalar eq('place', selected) correctly selects Source.
Please preserve and encode embedded membership values, or reject the unsupported form before executing the query. Add public-API tests for both membership operators covering reads, updates, deletes, and which records remain.
Validation: a targeted JDK 17/MongoDB 7.0.19 probe compiled the exact-head MongoQuery against the otherwise unchanged runtime from the previous review. It reproduced all six membership read/bulk-operation cases; scalar-equality and null-average controls passed. This was not a full module-suite run.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A membership of an embedded value matches a missing value, and a negated membership includes a missing outer value.
| */ | ||
| private Criterion membership(String property, Collection<?> values, boolean negated) { | ||
| if (values.stream().noneMatch(Objects::isNull)) { | ||
| return new In(property, values); |
There was a problem hiding this comment.
A membership selects an embedded value that has no identifier. It should match holders of that value. It matches holders that have none, because this turns the value into null. Compare the embedded value.
There was a problem hiding this comment.
Reproduced, in both reviews. With a nullable embedded place, inList('place', selected) returned the holder with no place, and notIn returned the source holder that it must exclude, in a read, an updateAll and a deleteAll; the query turned the embedded value into its null identifier. On 7.0.x inList returned no row and notIn was refused, so the form never worked. Fixed in f6b97e6 with the second option of the review: inList and notIn against a subquery are refused for an embedded property, before the subquery runs, with a message that names the property and says to compare with == or !=, which still compare the embedded value. AggregateSubquerySpec has the two operators with a read, an updateAll and a deleteAll each, and checks that no holder was changed or removed. With the refusal removed, those six rows fail.
| } | ||
| if (criterion instanceof NotIn notIn) { | ||
| Negation negation = new Negation(); | ||
| negation.add(membership(notIn.getProperty(), subqueryValues(notIn.getSubquery()), !negated)); |
There was a problem hiding this comment.
A negated membership returns a nonempty list, and a person has no age. That person should not be selected. They are, and a bulk delete would remove them. Leave them out.
There was a problem hiding this comment.
Reproduced and fixed in f6b97e6. A membership in a subquery now leaves out a row that has no value for the property, as SQL does, also inside a negation: notIn, not { inList }, not { notIn } and an or give the rows of the chart in AggregateSubquerySpec, and an updateAll and a deleteAll change only the people with another age, not the one without an age. On 7.0.x notIn against a subquery was refused, so this is new code of this pull request. It differs from a literal list on MongoDB, where a negation matches a row without the field; where.adoc says so. With the change removed, two rows fail.
|
|
||
| private Collection<?> subqueryValues(QueryableCriteria<?> subquery) { | ||
| List<?> rows = subquery.list(); | ||
| if ((rows == null || rows.isEmpty()) && selectsOneAggregateRow(subquery)) { |
There was a problem hiding this comment.
A sum is taken over rows whose value is missing. The sum is not a real zero. A negated membership against it should match nothing. It matches other ages, because this treats that sum as zero. Treat it as missing.
There was a problem hiding this comment.
Not changed. A sum of values that are all missing is 0 on MongoDB itself: Person.createCriteria().get { eq('firstName', 'Nobody'); projections { sum('age') } } returns 0 for a person without an age, while avg, max and min of it return null and a sum over no row at all is null. The subquery uses the value that the store returns for the aggregate, as a read of the same aggregate does, so it agrees with it. Making a subquery treat a sum of missing values as null would make it differ from the aggregate it stands for. If MongoDB should return SQL's null for such a sum, that is a change to the aggregate and belongs in its own issue; I can open it.
| return new Equals(property.getProperty(), value); | ||
| } | ||
| if (criterion instanceof NotEquals) { | ||
| return new NotEquals(property.getProperty(), value); |
There was a problem hiding this comment.
An inequality selects a standalone value that has an identifier, and the stored copy is embedded and has none. The holder of that same value should not be returned. It is, because this compares the two encodings. Compare the embedded value.
There was a problem hiding this comment.
I cannot build this case through a public query, so it is not reproduced. A standalone value that has an identifier, compared with an embedded copy of the same class, is not a form that the documentation defines; the pull request compares an embedded property with the value that the subquery selects, and that case works: ne('place', selected) of the value of the holder Source excludes Source and selects the holder with no place, which is MongoDB's own $ne. If you have the query, give it to me and I will add the row.
…y and leave out the row without a value inList and notIn against a subquery for an embedded property turned the embedded value into its null identifier, so a read, an updateAll and a deleteAll selected the wrong holders; the form is now refused before the subquery runs, and an embedded value is still compared with == and !=. A membership in a subquery now leaves out a row that has no value for the property, also inside a negation, as SQL does, where MongoDB matched it with $nin. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
@jdaugherty the membership of an embedded value is refused before the subquery runs, the second option of your review (f6b97e6). The probe on 7.0.x shows that the form never worked there: |
jamesfredley
left a comment
There was a problem hiding this comment.
The earlier membership of an embedded value is addressed. Requested changes. A sum of missing values is treated as zero, and an empty membership drops a missing outer value.
|
|
||
| private Collection<?> subqueryValues(QueryableCriteria<?> subquery) { | ||
| List<?> rows = subquery.list(); | ||
| if ((rows == null || rows.isEmpty()) && selectsOneAggregateRow(subquery)) { |
There was a problem hiding this comment.
A sum is taken over rows whose value is missing. The sum is not a real zero. A comparison against it should match nothing. It matches other ages, because this treats that sum as zero. Treat it as missing.
There was a problem hiding this comment.
Same as my reply on this thread at the earlier head: not changed. MongoDB's own sum of values that are all missing is 0, so the subquery selects the value that the aggregate returns, and the comparison agrees with a read of the same aggregate. Treating it as null here would make the subquery differ from the aggregate it stands for. If MongoDB's aggregate should return null for it, that is an issue of its own, and I can open it. Tell me if you want it.
| */ | ||
| private Criterion membership(String property, Collection<?> values, boolean negated) { | ||
| if (values.stream().noneMatch(Objects::isNull)) { | ||
| return known(property, new In(property, values), negated); |
There was a problem hiding this comment.
A negated membership returns no rows, and a person has no age. That person should be selected. They are left out, because this treats an empty list like a list that has a value. Keep the person.
There was a problem hiding this comment.
Fixed in dd8d4d5. A membership against a subquery that selects no row is false for every row, whether or not the row has a value, so its negation keeps the person without an age, as NOT IN () does in SQL. The test for a row with a value was wrapping the empty list too.
AggregateSubquerySpec has a new row: two people with an age and one without, and a subquery that selects no row. inList selects none, notIn and not { inList } select all three, and not { notIn } selects none. Before the change the person without an age was left out of the two negated forms. The full MongoDB core suite passes (603 tests), and codeStyle passes.
…se for every row A negated membership against a subquery that selects no row left out the row without a value, because the test for a row with a value wrapped the empty list too. In SQL a value is not in an empty list whether or not it is null, so its negation keeps the row. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
jamesfredley
left a comment
There was a problem hiding this comment.
The earlier empty membership is addressed. Requested changes. A comparison against a subquery includes a missing value, and a sum of missing values is treated as zero.
| return new Equals(property.getProperty(), value); | ||
| } | ||
| if (criterion instanceof NotEquals) { | ||
| return new NotEquals(property.getProperty(), value); |
There was a problem hiding this comment.
A person has no age, and a subquery returns a number. That person should not be selected by an inequality. They are, and a bulk delete would remove them. Leave them out.
|
|
||
| private Collection<?> subqueryValues(QueryableCriteria<?> subquery) { | ||
| List<?> rows = subquery.list(); | ||
| if ((rows == null || rows.isEmpty()) && selectsOneAggregateRow(subquery)) { |
There was a problem hiding this comment.
A sum is taken over rows whose value is missing. The sum is not a real zero. A comparison against it should match nothing. It matches age zero, because this treats that sum as zero. Treat it as missing.
…ongo-7.0.x # Conflicts: # grails-doc/src/en/guide/upgrading/upgrading60x.adoc # grails-skills/upgrade/skills/grails-upgrade/SKILL.md
…out a value, and the sum of no value is null, not zero A row with no value of the property was selected by != against a subquery, and by any comparison inside a negation, where SQL leaves it out: the comparison is unknown, and so is its negation. The comparison is now guarded as the membership already was, so that the row is neither selected nor changed by updateAll and deleteAll. MongoDB sums the missing values of a property to zero, where the sum of no value is null in SQL, so a comparison with that sum matched a row whose value is zero. A sum over a subquery in which no row has a value is read as a single null, as the average of no rows is, and the comparison selects nothing.
|
Pushed the next commit, which answers the review of 12-03 23:37 at dd8d4d5: a comparison against a subquery included the person with no age, and a sum of missing values was read as zero. Both are SQL semantics that the comparison did not follow, and both are fixed in A row with no value. A comparison with the value of a subquery is unknown for a row that has no value of the property, and so is its negation, so SQL selects it neither with A sum of missing values. MongoDB sums the missing values to zero, where the sum of a property that no row has a value of is null in SQL. A comparison with that sum matched the row whose age is zero. A subquery that sums a property of which no selected row has a value is now read as one null, as the average of no rows is, so the comparison, and its negation, select nothing. It is a count of the selected rows that have a value, so a sum that is zero because the values add up to zero is not touched. The class, not the sample.
|
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A sum check ignores the connection the subquery selected.
| if (projections == null || projections.size() != 1 || !(projections.get(0) instanceof SumProjection sum)) { | ||
| return false; | ||
| } | ||
| DetachedCriteria<?> withValue = new DetachedCriteria<>(subquery.getPersistentEntity().getJavaClass()); |
There was a problem hiding this comment.
A sum subquery that uses withConnection('archive') is counted on the default connection. If the archive has ages and the default collection does not, a real sum is replaced with null and the comparison matches nothing. Count on the connection the subquery selected.
…he connection of that subquery
A sum of a property that no row has a value of is null, as SQL sums no value, and MongoDB sums the missing values to zero, so the sum is told apart by asking
whether any row has the value. That question was asked of a new DetachedCriteria, which reads the default connection, so a sum subquery on another connection
(withConnection('archive')) was judged by the rows of the default collection: with ages in the archive and none in the default collection a real sum was replaced
with null and the comparison matched nothing, and with ages in the default collection and none in the archive the sum of nothing, zero, was compared. The question is
now asked of the subquery derived with a test that the value is there, which keeps its connection and its criteria, and a sum over no row that passes the test is
no row at all. AggregateSubqueryConnectionSpec has the 40 rows: the connection of the subquery (the default, the second with ages, with rows that have none, with no row)
and the connection that holds the rows, the four comparison operators, plain and negated; 8 of them fail with the previous code.
|
Pushed the next commit, which answers the review of 12-05 at fe13fa3. The sum check is code this pull request added, and it did read the wrong connection: to tell the sum of no value (null in SQL, and zero in MongoDB) from a real sum, it asked whether any row has the value, and it asked a new The change is one question asked in the right place. The check no longer builds a criteria of its own. It derives the subquery with The table is
With the previous check 8 rows fail, four of each group: the sum of rows with no age on the second connection is compared as zero, and the sum of the second connection is replaced with null when the default collection has no ages. With this commit all 40 pass.
|
✅ All tests passed ✅🏷️ Commit: 5dc0028 Learn more about TestLens at testlens.app/docs. |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. The sum check now uses the subquery's connection. A sum that is limited to a null row is still treated as zero.
| return null; | ||
| } | ||
| }; | ||
| List<?> rows = detached.where(hasValue).list(); |
There was a problem hiding this comment.
Records ordered by name with ages null then 10, and a subquery sort('name').max(1).sum('age'), should sum to null. The extra non-null filter runs before the limit, so it sees the second row and keeps the zero. A comparison then matches rows it should miss. Apply the limit before deciding the sum is null.
Fixes #16809 for MongoDB on 7.0.x. This is the MongoDB half of #16875, which holds it on 8.0.x together with Neo4j: by the dev@ rule for fixes that change results, a wrong result goes to the oldest branch that has it, and 7.0.x does not build Neo4j.
Problem
where { age > avg(age) }and the other aggregate subqueries documented forwherereturned no rows on MongoDB, because the subquery was compared as an object and not run. On unchanged 7.0.x, all 23 features of this pull request'sAggregateSubquerySpecfail: the comparisons return no rows,!=against an empty subquery returns every row,notInthrowsQueries of type NotIn are not supported,existsis not rejected by name, andwhere { age != max(age) }.deleteAll()deletes every row.Change
MongoQueryruns the subqueries of a query first and builds its filter from the result, for a read, forget(), and fordeleteAllandupdateAll, which select the rows alist()of the same query finds.==,!=,>,>=,<,<=againstavg,max,minandsum, andinList/notInagainst a subquery that selects a property, are supported. A comparison against a subquery that returns more than one row, andexists,notExists,allandsome, throw anInvalidDataAccessResourceUsageExceptionthat names the form. A subquery that returns no row matches no row, as in SQL, and so does its negation.The change is in
MongoQueryonly.Results that change
Queries with a comparison against a subquery on MongoDB return the rows the query asks for instead of none,
!=against an empty subquery no longer returns every row, anddeleteAllno longer deletes rows the read does not find. The upgrade guide has a note under Grails 7.0.18 and the upgrade skill the same entry. By the rule for fixes that change results, this needs a second reviewer.Branch policy: the new throws replace wrong rows for subquery forms that MongoDB does not run, which #16809 allows.
Since the review of a0f02c0:
inListandnotInagainst a subquery for an embedded property are refused, since they selected the wrong holders (on 7.0.xinListreturned no row andnotInwas refused); and a membership in a subquery leaves out a row that has no value for the property, also undernot, as SQL does, where MongoDB matches it with a negation. A sum of values that are all missing is the0that the aggregate of MongoDB returns, and the subquery uses it as the aggregate does.Not in this pull request
Association blocks behave as on 7.0.x: a subquery inside one is not run, so
notInof a subquery is refused there, and anotor anorinside an embedded block matches no owner. Those changes are in #17189, together with the fix for #17187 (a negated condition on an embedded value matches an owner that has no such value, which is the case on 7.0.x without this change).Tests
AggregateSubquerySpecfor MongoDB (23 features,addressandagenullable because 7.0.x validates an embedded null) passes here; on unchanged 7.0.x 22 of them fail. The other pins that anotInsubquery inside an embedded block is refused, as it is there. The MongoDB core module passes (592 tests), and so doescodeStyle. Nothing outside the MongoDB module changes, apart from the upgrade notes.Review notes
$ne,$nin,$notand$norreturn missing and null fields ($ne,$nin,$not,$nor, null fields) and Hibernate 5 does not. That is a difference between the stores and not part of this change; it is documented, not changed.https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL