简体   繁体   English

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

[英]How to do this aggregation in spring data mongo db?

How to do this aggregation in Spring Data MongoDB? 如何在Spring Data MongoDB中进行此聚合?

db.order.aggregate([
    { $match: { quantity: { $gt:1 } } },
    { $group: { _id: "$giftCard", count: { $sum: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. 请使用获取mongoOperations对象的方式更改getMongoConnection()。 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:- 使用的Spring数据版本: -

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

The following aggregation operation is a Spring Data MongoDB equivalent: 以下聚合操作是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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM