如何在spring数据mongo db中进行这种聚合?

时间:2016-09-12 07:29:31

标签: java spring mongodb spring-data spring-data-mongodb

如何在Spring Data MongoDB中进行此聚合?

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

2 个答案:

答案 0 :(得分:5)

以下是问题中提到的查询的示例代码。

请使用获取mongoOperations对象的方式更改getMongoConnection()。我刚刚在底部添加了我的代码供您参考。

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;

    }

我的参考连接方法: -

public MongoOperations getMongoConnection() {

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

使用的Spring数据版本: -

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

示例输出: -

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

答案 1 :(得分:2)

以下聚合操作是Spring Data MongoDB的等价物:

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();