Search code examples
spring-dataaggregation-frameworkspring-webfluxspring-data-mongodb

Map aggregate query result to correct attributes of POJO


I have a collection named Location which has couple of attributes of which I want to fetch only country code and country name.

When I'm using below aggregation query in Spring Data, all the attributes are getting mapped to the _id attribute of Location.java and not to individual countryCode and countryName attribute of the List. Please help me resolve the same.

@Repository
public class AggregateQueryRepository {
    
@Autowired
ReactiveMongoTemplate reactiveMongoTemplate;
 
public Flux<Location> getAllCountryCodeAndCountry() {
        Aggregation aggregation = newAggregation(group("countryCode", "countryName")
        );
        return reactiveMongoTemplate.aggregate(aggregation, "location", Location.class);
    }
}

Currently each object of the result looks like below:

{ "_id": "{\"countryCode\": \"IN\", \"countryName\": \"India\"}" }

I want to map it to something like below:

{
{ "_id": null,
"countryCode": "ÏN"
"countryName": "India"
},
....
.....
}

Solution

  • If you must have it separately, you can consider using $first aggregation accumulator:

    Aggregation aggregation = newAggregation(
        group("countryCode", "countryName")
            .first("countryCode").as("countryCode")
            .first("countryName").as("countryName")
    );
    
    return reactiveMongoTemplate.aggregate(aggregation, "location", Location.class);
    

    ...or alternatively $replaceRoot aggregation stage:

    Aggregation aggregation = newAggregation(
        group("countryCode", "countryName"),
        replaceRoot("_id")
    );
    
    return reactiveMongoTemplate.aggregate(aggregation, "location", Location.class);