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

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

Introduction

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

Prototype

public static ProjectionOperation project(Class<?> type) 

Source Link

Document

Creates a new ProjectionOperation including all top level fields of the given given Class .

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  va 2s  .  co 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));

}