如何在 spring 数据 mongo 数据库中进行聚合?

How to do this aggregation in spring data mongo db?

如何在 Spring 数据 MongoDB 中进行聚合?

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

以下聚合操作是 Spring 数据 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();

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

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

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}]