Search code examples
mongodbspring-data-mongodbspring-mongodb

Spring Data Mongo - Custom AggregtionOption not working


I tried creating a Custom AggregationOperation based on https://github.com/krishnaiitd/learningJava/tree/master/spring-boot-sample-data-mongodb When I used a custom aggregation in my aggregation for a lookup, it threw an exception saying the "as" field is not found on the entity.

If anybody has tried using custom AggregationOperation please share your code or let me know where I am going wrong.

Below is my code,

String lookup = "{ $lookup : { from: 'ITEM', localField : 'item_id', foreignField : '_id', as : 'item' } }";
TypedAggregation<Order> aggregation = Aggregation.newAggregation(Order.class, 
        new CustomAggregationOperation(lookup),
        unwind("item", false));

The exception:

org.springframework.data.mapping.PropertyReferenceException: No property item found for type Order!

Solution

  • A TypedAggregation is a special Aggregation that holds information of the input aggregation type.

    https://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/aggregation/TypedAggregation.html

    That means that Spring will verify after each stage that your documents have not changed the structure.

    Since you are trying transform original document, you need to use a standard Aggregation.

    Aggregation aggregation = Aggregation.newAggregation(
        new CustomAggregationOperation(lookup),
        unwind("item", false)
    );
    
    List<Order> result = mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(Order.class), Order.class).getMappedResults();