当前位置:   article > 正文

MongoDB —— Spring Boot JPA与MongoTemplate分组、排序、聚合、分页_mongodb jpa排序

mongodb jpa排序

MongoDB —— Spring Boot JPA与MongoTemplate分组、排序、聚合、分页

简介

通过MongoTemplate实现分组、排序、聚合、分页等功能;

Action

加依赖

<!-- MongoDB begin -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- MongoDB end -->
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

改配置

spring:
  data:
    mongodb:
      # 链接的地址和库
      uri: mongodb://127.0.0.1:27017/metrics
  • 1
  • 2
  • 3
  • 4
  • 5

写代码

...
...

    /**
     * 处理group时使用流式操作,务必注意顺序
     * @param params 条件
     * @param pageBean 分页信息
     * @param sortMap 排序信息(在调用前进行了处理,将分页字段和分页类型进行了处理)
     * @return
     */
    protected Aggregation getGeneralAggregation(Map<String, Object> params,
                                                PageBean pageBean,
                                                Map<String, String> sortMap) {

        // 实例化条件集合
        List<AggregationOperation> operations = new ArrayList<>();

        // 条件搜索逻辑
        List<Criteria> criteriaList = new ArrayList<>();
        if (params != null && params.size() > 0) {
            log.debug("查询参数:" + params);
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getKey() != null && entry.getValue() != null) {
                    String key = entry.getKey();
                    if("startTime".equals(key)) {
                        criteriaList.add(Criteria.where(entry.getKey()).gt(entry.getValue()));
                    } else
                    if("endTime".equals(key)) {
                        criteriaList.add(Criteria.where(entry.getKey()).lt(entry.getValue()));
                    } else {
                        Pattern pattern = Pattern.compile("^.*"+entry.getValue()+".*$", Pattern.CASE_INSENSITIVE);
                        Criteria criteria = new Criteria();
                        criteriaList.add(criteria.orOperator(Criteria.where(entry.getKey()).regex(pattern)));
                    }
                }
            }
            operations.add(Aggregation.match(new Criteria().andOperator(criteriaList.toArray(new Criteria[criteriaList.size()]))));
        }

        // 查询的字段
        operations.add(
                Aggregation.project( "serviceName", "endpointName")
        );
        String[] group = {"serviceName", "endpointName"};
        String sortColumn = sortMap.get("sortColumn");
        String sortType = sortMap.get("sortType");
        // 分组,聚合逻辑
        operations.add(
        		// 根绝grop分组,然后取平均avg(...)
                Aggregation.group(group).avg(new AggregationExpression() {
                    @Override
                    public Document toDocument(AggregationOperationContext context) {
                        if("qpsList".equals(sortColumn)) {
                        	// 求合
                            return new Document("$sum",
                            		// 将qps类型转换为dobule,用于计算合
                                    new Document("$toDouble", "$qps"));
                        }
                        return new Document("$sum", "$aveResponseTime");
                    }
                }).as("avgAmount")
                // 将第一个serviceName获取,分组之后取第一个
                .first("serviceName").as("serviceName")
                // 将第一个endpointName获取,分组之后取第一个
                .first("endpointName").as("endpointName"));
        // 需返回的字段,as后的
        operations.add(Aggregation.project( "serviceName","endpointName","avgAmount"));

        // 排序
        if(StringUtils.isBlank(sortType) || "ASC".equals(sortType)) {
            operations.add(Aggregation.sort(Sort.by(Sort.Direction.ASC, "avgAmount")));
        } else {
            operations.add(Aggregation.sort(Sort.by(Sort.Direction.DESC, "avgAmount")));
        }

        // 分页逻辑
        if (pageBean != null) {
            operations.add(Aggregation.skip((long) (pageBean.getPageNum() > 0
                    ? (pageBean.getPageNum() - 1) * pageBean.getPageSize()
                    : 0)));
            operations.add(Aggregation.limit(pageBean.getPageSize()));
        }
        Aggregation aggregation = Aggregation.newAggregation(operations);
        return aggregation;
    }
...
...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87

总结

  • 更加复杂的MongoDB处理:
    https://www.coder.work/article/5661161

  • 有什么想说的?
    如果qps定义的是double类型,就不需要转换了

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/55972
推荐阅读
相关标签
  

闽ICP备14008679号