赞
踩
通过MongoTemplate实现分组、排序、聚合、分页等功能;
<!-- MongoDB begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- MongoDB end -->
spring:
data:
mongodb:
# 链接的地址和库
uri: mongodb://127.0.0.1:27017/metrics
... ... /** * 处理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; } ... ...
更加复杂的MongoDB处理:
https://www.coder.work/article/5661161
有什么想说的?
如果qps定义的是double类型,就不需要转换了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。