加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 04:35:55 所属栏目:Java 来源:网络整理
导读:如何在 Spring Data MongoDB中进行此聚合? db.order.aggregate([ { $match: { quantity: { $gt:1 } } },{ $group: { _id: "$giftCard",count: { $sum:1 } } }]) 解决方法 以下是问题中提到的查询的示例代码. 请使用获取mongoOperations对象的方式更改getMon
如何在 Spring Data MongoDB中进行此聚合?

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

解决方法

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

请使用获取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}]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读