Skip to content

fix(mongodb): a comparison against a subquery in a where query runs the subquery - #17161

Open
borinquenkid wants to merge 22 commits into
7.0.xfrom
fix/where-subquery-mongo-7.0.x
Open

borinquenkid wants to merge 22 commits into
7.0.xfrom
fix/where-subquery-mongo-7.0.x

Conversation

@borinquenkid

@borinquenkid borinquenkid commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

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 for where returned 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's AggregateSubquerySpec fail: the comparisons return no rows, != against an empty subquery returns every row, notIn throws Queries of type NotIn are not supported, exists is not rejected by name, and where { age != max(age) }.deleteAll() deletes every row.

Change

MongoQuery runs the subqueries of a query first and builds its filter from the result, for a read, for get(), and for deleteAll and updateAll, which select the rows a list() of the same query finds. ==, !=, >, >=, <, <= against avg, max, min and sum, and inList / notIn against a subquery that selects a property, are supported. A comparison against a subquery that returns more than one row, and exists, notExists, all and some, throw an InvalidDataAccessResourceUsageException that names the form. A subquery that returns no row matches no row, as in SQL, and so does its negation.

The change is in MongoQuery only.

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, and deleteAll no 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: inList and notIn against a subquery for an embedded property are refused, since they selected the wrong holders (on 7.0.x inList returned no row and notIn was refused); and a membership in a subquery leaves out a row that has no value for the property, also under not, as SQL does, where MongoDB matches it with a negation. A sum of values that are all missing is the 0 that 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 notIn of a subquery is refused there, and a not or an or inside 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

AggregateSubquerySpec for MongoDB (23 features, address and age nullable because 7.0.x validates an embedded null) passes here; on unchanged 7.0.x 22 of them fail. The other pins that a notIn subquery inside an embedded block is refused, as it is there. The MongoDB core module passes (592 tests), and so does codeStyle. Nothing outside the MongoDB module changes, apart from the upgrade notes.

Review notes

  • Embedded blocks (below) are not changed.
  • A property that is there with a null value: MongoDB's own $ne, $nin, $not and $nor return 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

…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

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@borinquenkid

Copy link
Copy Markdown
Member Author

@jamesfredley Fixed, and not only for address { notIn('city', names) }: the same hole was in every negated condition on an embedded value, because MongoDB's $ne, $nin, $not and $nor match a missing field. A negation on a path through an embedded property now also requires that embedded 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.

I wrote the table first, CriteriaEmbeddedNegationSpec in the TCK, and took the expected values from Hibernate 5, which agrees with all 19 rows; 15 of them failed on MongoDB before the change and all pass now:

  • Form: an association block (address { }), a dotted property (ne('address.city', x), not { }), a detached criteria, and a where (address.city != x).
  • Operator: ne, notIn (a list and a subquery), not { eq }, not { inList }, on the first and the second property of the embedded value.
  • Position: top level, an or with a branch that has no embedded value, an or of a block and its negation, an and in either order, a negated block, and a count.
  • Data: an owner with the value in each store, one with another value, and one with no value.

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; where { !(address.city == x) } throws on Hibernate 5 and is not part of the table. The upgrade note under 7.0.18 and the skill entry describe the change, and AggregateSubquerySpec now holds an owner with no address.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

…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
@borinquenkid

borinquenkid commented Nov 24, 2026 •

Copy link
Copy Markdown
Member Author

Pushed 6e2cb3a. not { and { eq('name', 'Bob'); eq('address.city', 'Paris') } } matches Nina now: she has no address and her name is not Bob.

The embedded value was required for the whole negated group. A $nor over an $and, an $or or several fields is now pushed down to its conditions first, as De Morgan does (the negation of a conjunction is a disjunction of the negations, of a disjunction a conjunction of them), and each negated condition requires the embedded value it goes through. Nina's name condition is true for her, so she matches; a Bob who lives in Paris fails both and is left out.

CriteriaEmbeddedNegationSpec has six new rows on a fixture with two Bobs and Nina: an and of a name and a dotted property, of a name and a block, the same in a DetachedCriteria, an and whose name condition is the one that fails for Nina, an or, and an or beside a matching name. Their expected values come from Hibernate 5 (one I had guessed wrong, a not holding two conditions negates each of them, and I took Hibernate 5's value). Three of them fail without the change. Hibernate 5 core (717 tests), MongoDB core (618) and codeStyle are green.

Not covered here: a property that is there with a null value. MongoDB returns that owner for ne, nin, not and nor, and Hibernate 5 does not. That is how MongoDB defines the operators, so it is a difference between the stores and not a defect of this change; I would record it in the documentation and not change it here. The MongoDB manual (all pages under https://www.mongodb.com/docs/manual/):

  • $ne: selects documents where the value is not the given one, and that includes documents where the field does not exist.
  • $nin: selects documents where the value is not in the array or the field does not exist.
  • $not: selects documents that do not match the expression, including documents without the field; its example is { runtime: { $not: { $gt: 180 } } }.
  • $nor: selects documents that fail every expression, including documents that lack the fields, unless $exists is used.
  • query for null or missing fields: section "Equality Filter", { field: null } matches a field that is null or missing; section "Non-Equality Filter", { field: { $ne: null } } is the query for fields that exist and are not null. That second form is the guard this change adds for an embedded value.

For Hibernate 5 there is no documentation of the null case either; the value is the one the spec measures: CriteriaEmbeddedNegationSpec line 33 says the expected values are Hibernate 5's, and the new rows start at line 111. The change itself is distributeNegations, MongoQuery.java line 770, and the matrix is CriteriaSemanticMatrixSpec line 47.

Because this has come one shape at a time, the last commit adds CriteriaSemanticMatrixSpec to the TCK: 686 criteria from one grammar (a leaf eq, ne or inList on a name, an age or an embedded city; and, or and not of up to two leaves, and of a group and a leaf; the city as a dotted property and as a block; a criteria builder and a detached criteria), each compared with a small evaluator that applies SQL three-valued logic, and not with a value written per query. Hibernate 5 matches the evaluator on every query. Against the MongoQuery before the last fix it reports 72 mismatches, all not { and … } and not { or … } over an embedded value; with the fix, none. It is gated to Hibernate 5 and MongoDB for now; adding another store is one line in its @Requires.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@borinquenkid

Copy link
Copy Markdown
Member Author

I could not reproduce this one, so there is no code change in this push, only rows (cb97fd7).

The line you cite, MongoQuery.java line 873, looks the part of the field up with getPropertyByName, and for a property stored under another name that finds it: AbstractPersistentEntity.getPropertyByName, lines 401 to 406 falls back to mappedPropertiesByName, which is filled with each property under its stored name (line 188). I also checked it directly on the unchanged code: for address field: 'addr', getPropertyByName('addr') and getPropertyByName('address') both return the embedded property.

The new spec, EmbeddedNegationStoredNamesSpec, maps the address as addr (line 123), its city as town (line 138), a geo value inside it as g and the zone as zn, and holds an owner with no address. Your case is line 79: address { notIn('city', cities(['Paris'])) }, where the list is a subquery as notIn takes it, and it returns only the owner whose city is not in the list, not the owner with no address. The same holds for a detached criteria (line 82), a block in a block (line 83) and an or (line 84). All 16 rows pass on the code as it was before this push; grails-data-mongodb-core runs 637 tests green.

If the mapping you ran differs (for instance how addr is declared), please send it and I will turn it into a row; a row that fails is a bug to fix here. One separate limit I found while checking: a dotted property through an embedded property stored under another name, eq('address.city', 'Paris'), finds nothing, with or without a negation. It is not about negation and I have left it out of this pull request.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@borinquenkid

Copy link
Copy Markdown
Member Author

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, MongoQuery.java line 873, finds a property stored under another name: AbstractPersistentEntity.getPropertyByName, lines 401 to 406 falls back to mappedPropertiesByName, filled with each property under its stored name (line 188). In EmbeddedNegationStoredNamesSpec the address is stored as addr (line 123), and address { notIn('city', cities(['Paris'])) } (line 79 before this push, now a few lines lower) returns only the owner whose city is not in the list, not the owner with no address, on the code as it was.

One thing about the form in your comment: notIn('city', names) with names a list is not a method of the criteria builder (MongoCriteriaBuilder.notIn(String, ArrayList): no signature; it takes a closure or a QueryableCriteria) and not of DetachedCriteria either, so I tested the forms that exist for a list: not { inList(...) } in a block, in a detached criteria (line 79 of this push) and the where forms !(address.city in ['Paris']) (line 80) and address.city != 'Paris' (line 81); all return only the owner whose city differs. The new rows are the where query and the detached criteria; 640 tests of grails-data-mongodb-core and codeStyle are green.

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 jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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 sbglasius left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@borinquenkid

Copy link
Copy Markdown
Member Author

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 jdaugherty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +559 to +562
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 jdaugherty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@borinquenkid

Copy link
Copy Markdown
Member Author

@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: inList returned no row and notIn was refused. The refusal is a new throw for an input that ran, and it ran with a wrong result, so I put it in the note: where.adoc, the 7.0.18 note and the upgrade skill say it. AggregateSubquerySpec covers both operators for a read, an updateAll and a deleteAll, and checks which holders remain.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@borinquenkid

Copy link
Copy Markdown
Member Author

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 MongoQuery.

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 != nor with not { age > ... }. MongoDB matches such a row with $ne and with any comparison inside a negation, and a bulk delete went with the read. The comparison is now guarded as the membership was: the row is told apart, so that it fails the test with an even number of negations around it and passes the test with an odd number, and the negation fails it. A row with no age is neither read, updated nor deleted by the comparison.

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. AggregateSubquerySpec has a table of 180 rows: five subqueries (the maximum, the minimum, the average, the sum, and the sum of no value), the six comparisons, plain and under not, in a read, an updateAll and a deleteAll, over five people (ages 10, 20, 30, zero, and no age). The expected rows are computed by SQL's rules in the spec, not written by hand. With the change reverted 105 rows fail: all 33 of the sum of no value, and 18 for each of the other four subqueries; the person with no age and the person whose age is zero are the rows that tell the cases apart.

grails-data-mongodb-core passes (801 tests) and codeStyle is clean. I merged 7.0.x first; the two upgrade files conflicted, and I kept both sides.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@borinquenkid

Copy link
Copy Markdown
Member Author

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 DetachedCriteria, which reads the default connection. A subquery on withConnection('archive') was judged by the default collection.

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 where { isNotNull(property) }, which keeps the connection, the criteria and the projection of the subquery, and runs it: a sum over no row that passes the test is no row at all, and a sum over rows that have the value is one row. So the connection of the subquery is the one that answers, and the code of the check does not name a connection.

The table is AggregateSubqueryConnectionSpec (the Mongo specs with two connections), 40 rows, with the expectation computed in the spec:

  • the subquery on the connection of the rows (the first one, sum 110) and on the second one, which holds ages (sum 50), rows that have no age, or no row at all, each with the four comparison operators, plain and negated: 32 rows;
  • the case of your review: the rows and the subquery on the second connection, which has ages (5, 20 and 30), and the default connection holding a person with no age, with the four operators, plain and negated: 8 rows.

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.

grails-data-mongodb-core passes and codeStyle is clean.

@testlens-app

testlens-app Bot commented Dec 5, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: 5dc0028
▶️ Tests: 54211 executed
⚪️ Checks: 58/58 completed


Learn more about TestLens at testlens.app/docs.

@jamesfredley jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

5 participants