spring-projects / spring-data-mongodb

Provides support to increase developer productivity in Java when using MongoDB. Uses familiar Spring concepts such as a template classes for core API usage and lightweight repository style data access.
https://spring.io/projects/spring-data-mongodb/
Apache License 2.0
1.59k stars 1.07k forks source link

Aggregation with `$unwind` and `$project` causes `IllegalArgumentException` #4714

Closed shollander closed 3 weeks ago

shollander commented 1 month ago

given the following data model:

@Document
public record TestRecord(@Id String field1, String field2, LayerOne layerOne) {
    public record LayerOne(List<LayerTwo> layerTwo) { }

    public record LayerTwo(LayerThree layerThree) { }

    public record LayerThree(int fieldA int fieldB) { }
}

The following aggregation query should work (and does work in the shell), but throws an error:

Aggregation agg = Aggregation.newAggregation(
    unwind("layerOne.layerTwo"),
    project().and("layerOne.layerTwo.layerThree").as("layerOne.layerThree"),
    sort(DESC, "layerOne.layerThree.fieldA")
    );
mongoTemplate.aggregate(agg, TestRecord.class, Document.class);

The following error is produced:

java.lang.IllegalArgumentException: Invalid reference: 'layerOne.layerThree.fieldA'
    at org.springframework.data.mongodb.core.aggregation.ExposedFieldsAggregationOperationContext.getReference(ExposedFieldsAggregationOperationContext.java:108)
christophstrobl commented 3 weeks ago

@shollander thank you for raising the issue. we'll have a look.