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

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

Introduction

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

Prototype

public static LimitOperation limit(long maxElements) 

Source Link

Document

Creates a new LimitOperation limiting the result to the given number of elements.

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  w  w  w . j av a2s . com
 *      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));

}