Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do this aggregation in spring data mongo db?

How to do this aggregation in Spring Data MongoDB?

db.order.aggregate([
    { $match: { quantity: { $gt:1 } } },
    { $group: { _id: "$giftCard", count: { $sum:1 } } }
])
like image 535
Praveen Avatar asked Sep 12 '16 07:09

Praveen


2 Answers

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}]
like image 68
notionquest Avatar answered Nov 15 '22 22:11

notionquest


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();
like image 33
chridam Avatar answered Nov 15 '22 22:11

chridam