Example usage for org.springframework.data.mongodb.core.aggregation Aggregation unwind

List of usage examples for org.springframework.data.mongodb.core.aggregation Aggregation unwind

Introduction

In this page you can find the example usage for org.springframework.data.mongodb.core.aggregation Aggregation unwind.

Prototype

public static UnwindOperation unwind(String field) 

Source Link

Document

Factory method to create a new UnwindOperation for the field with the given name.

Usage

From source file:org.ingini.mongodb.spring.example.aggregation.TestAggregationFramework.java

/**
 * Example taken from https://github.com/mongodb/mongo-ruby-driver/wiki/Aggregation-Framework-Examples
 * Command line import: mongoimport --drop --db aggregation_test_db --collection name_days name_days.json
 * <p>//from ww w. j  a v  a 2  s  .  c o  m
 *      db.name_days.aggregate({$project : {names : 1, _id : 0}},
 *                             {$unwind : '$names'},
 *                             {$group : {_id: '$names', counter: {$sum: 1}}},
 *                             {$sort : {counter: -1}},
 *                             {$limit : 10});
 * </p>
 */
@Test
public void shouldFindThe10MostCommonNames() {
    //GIVEN
    CollectionManager.cleanAndFill(mongoTemplate.getDb(), "name_days.json", NameData.COLLECTION_NAME);
    int limit = 10;

    //WHEN
    AggregationResults<AggregatedNameData> aggregationResult = mongoTemplate.aggregate(
            Aggregation.newAggregation(NameData.class, Aggregation.project("names").andExclude("_id"),
                    Aggregation.unwind("names"), Aggregation.group("names").count().as("counter"),
                    Aggregation.sort(Sort.Direction.DESC, "counter"), Aggregation.limit(limit)),
            AggregatedNameData.class);

    //THEN
    assertThat(aggregationResult.getMappedResults()).hasSize(10);
    assertThat(aggregationResult.getMappedResults().get(0)).isEqualTo(new AggregatedNameData("Jana", 21));

}