Search in sources :

Example 1 with LimitOperation

use of org.springframework.data.mongodb.core.aggregation.LimitOperation 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));
}
Also used : Aggregation.newAggregation(org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) ProjectionOperation(org.springframework.data.mongodb.core.aggregation.ProjectionOperation) SortOperation(org.springframework.data.mongodb.core.aggregation.SortOperation) LimitOperation(org.springframework.data.mongodb.core.aggregation.LimitOperation) StatePopulation(org.baeldung.aggregation.model.StatePopulation) Sort(org.springframework.data.domain.Sort) GroupOperation(org.springframework.data.mongodb.core.aggregation.GroupOperation) Test(org.junit.Test)

Aggregations

StatePopulation (org.baeldung.aggregation.model.StatePopulation)1 Test (org.junit.Test)1 Sort (org.springframework.data.domain.Sort)1 Aggregation (org.springframework.data.mongodb.core.aggregation.Aggregation)1 Aggregation.newAggregation (org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation)1 GroupOperation (org.springframework.data.mongodb.core.aggregation.GroupOperation)1 LimitOperation (org.springframework.data.mongodb.core.aggregation.LimitOperation)1 ProjectionOperation (org.springframework.data.mongodb.core.aggregation.ProjectionOperation)1 SortOperation (org.springframework.data.mongodb.core.aggregation.SortOperation)1