13.07.2015 Views

Spring Data MongoDB - Spring Web Services - Parent - SpringSource

Spring Data MongoDB - Spring Web Services - Parent - SpringSource

Spring Data MongoDB - Spring Web Services - Parent - SpringSource

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

please define productname in your docbook file!This example is based on the Largest and Smallest Cities by State example from the <strong>MongoDB</strong>Aggregation Framework documentation. We added additional sorting to produce stable results withdifferent <strong>MongoDB</strong> versions. Here we want to return the smallest and largest cities by population foreach state, using the aggregation framework. This example demonstrates the usage of grouping, sortingand projections (selection).class ZipInfo {String id;String city;String state;@Field("pop") int population;@Field("loc") double[] location;}class City {String name;int population;}class ZipInfoStats {String id;String state;City biggestCity;City smallestCity;}import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;TypedAggregation aggregation = newAggregation(ZipInfo.class,group("state", "city").sum("population").as("pop"),sort(ASC, "pop", "state", "city"),group("state").last("city").as("biggestCity").last("pop").as("biggestPop").first("city").as("smallestCity").first("pop").as("smallestPop"),project().and("state").previousOperation().and("biggestCity").nested(bind("name", "biggestCity").and("population", "biggestPop")).and("smallestCity").nested(bind("name", "smallestCity").and("population", "smallestPop")),sort(ASC, "state"));AggregationResults result = mongoTemplate.aggregate(aggregation,ZipInfoStats.class);ZipInfoStats firstZipInfoStats = result.getMappedResults().get(0);Example 5.18 Aggregation Framework Example 2• The class ZipInfo maps the structure of the given input-collection. The class ZipInfoStatsdefines the structure in the desired output format.• As a first step we use the group operation to define a group from the input-collection. The groupingcriteria is the combination of the fields "state" and "city" which forms the id structure of thegroup. We aggregate the value of the "population" property from the grouped elements with byusing the sum operator saving the result in the field "pop".1.4.0.BUILD-SNAPSHOT<strong>Spring</strong> <strong>Data</strong> <strong>MongoDB</strong> -Reference Documentation 58

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!