区分先后条件顺序,这是个坑!
/*** 测试聚合*/@Testpublic void testAggregation() {String format_DateTime = "yyyy-MM-dd HH:mm:ss";DateTimeFormatter df = DateTimeFormatter.ofPattern(format_DateTime);LocalDateTime localDateTime = LocalDateTime.parse("2023-11-23 12:13:08", df);LocalDateTime endTime = LocalDateTime.parse("2022-11-23 12:13:08", df);// Query query = new Query();
// query.fields().exclude("_id");Criteria criteria = Criteria.where("name").is("a");
// criteria.andOperator(
// Criteria.where("time").gte(localDateTime),
// Criteria.where("time").lte(endTime));
// query.addCriteria(criteria);AggregationOperation match = Aggregation.match(criteria);List<AggregationOperation> operations = new ArrayList<>();operations.add(match); //区分先后条件顺序,这是个坑!operations.add(Aggregation.group("sex")/*.first("equipmentId").as("equipmentId")*/.sum("sex").as("sex").sum("age").as("age"));Aggregation aggregation = Aggregation.newAggregation(operations);AggregationResults<Document> aggregate = mongoTemplate.aggregate(aggregation, "c3", Document.class);List<Document> mappedResults = aggregate.getMappedResults();log.debug("BaBiaoChongQingCeBaoYiQuery 聚合合计查询结果 {}", JSONUtil.toJsonStr(aggregate));System.out.println("-----------------" + (CollectionUtils.isEmpty(mappedResults) ? null : mappedResults.get(0)));System.out.println("==============" + mappedResults);}