How to do this aggregation in spring data mongo db?

10,570

Solution 1

Here is the sample code for the query mentioned in the question.

Please change the getMongoConnection() with your way of getting the mongoOperations object. I have just added my code at the bottom for your reference.

public Boolean getOrderGiftCardCount(Integer quantity) {

        MongoOperations mongoOperations = getMongoConnection();

        MatchOperation match = new MatchOperation(Criteria.where("quantity").gt(quantity));
        GroupOperation group = Aggregation.group("giftCard").sum("giftCard").as("count");

        Aggregation aggregate = Aggregation.newAggregation(match, group);

        AggregationResults<Order> orderAggregate = mongoOperations.aggregate(aggregate,
                "order", Order.class);

        if (orderAggregate != null) {
            System.out.println("Output ====>" + orderAggregate.getRawResults().get("result"));
            System.out.println("Output ====>" + orderAggregate.getRawResults().toMap());
        }

        return true;

    }

My connection method for reference:-

public MongoOperations getMongoConnection() {

        return (MongoOperations) new AnnotationConfigApplicationContext(SpringMongoConfig.class)
                .getBean("mongoTemplate");
    }

Spring data version used:-

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.9.1.RELEASE</version>
    </dependency>

Sample output:-

Output ====>[ { "_id" : 2.0 , "count" : 2.0} , { "_id" : 1.0 , "count" : 2.0}]

Solution 2

The following aggregation operation is a Spring Data MongoDB equivalent:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

Aggregation agg = newAggregation(
    match(where("quantity").gt(1)),
    group("giftCard").count().as("count")
);

AggregationResults<OrderCount> results = mongoTemplate.aggregate(
    agg, "order", OrderCount.class
);
List<OrderCount> orderCount = results.getMappedResults();
Share:
10,570
Praveen
Author by

Praveen

Just a freelance programmer

Updated on June 26, 2022

Comments

  • Praveen
    Praveen almost 2 years

    How to do this aggregation in Spring Data MongoDB?

    db.order.aggregate([
        { $match: { quantity: { $gt:1 } } },
        { $group: { _id: "$giftCard", count: { $sum:1 } } }
    ])