use of org.springframework.data.mongodb.core.aggregation.ProjectionOperation in project tutorials by eugenp.
the class ZipsAggregationLiveTest method whenStateWithLowestAvgCityPopIsND_theSuccess.
@Test
public void whenStateWithLowestAvgCityPopIsND_theSuccess() {
GroupOperation sumTotalCityPop = group("state", "city").sum("pop").as("cityPop");
GroupOperation averageStatePop = group("_id.state").avg("cityPop").as("avgCityPop");
SortOperation sortByAvgPopAsc = sort(new Sort(Direction.ASC, "avgCityPop"));
ProjectionOperation projectToMatchModel = project().andExpression("_id").as("state").andExpression("avgCityPop").as("statePop");
LimitOperation limitToOnlyFirstDoc = limit(1);
Aggregation aggregation = newAggregation(sumTotalCityPop, averageStatePop, sortByAvgPopAsc, limitToOnlyFirstDoc, projectToMatchModel);
AggregationResults<StatePopulation> result = mongoTemplate.aggregate(aggregation, "zips", StatePopulation.class);
StatePopulation smallestState = result.getUniqueMappedResult();
assertEquals("ND", smallestState.getState());
assertTrue(smallestState.getStatePop().equals(1645));
}
Aggregations