```
@ApiOperation(value = "分组测试", notes = "分组测试", httpMethod = "GET")
@GetMapping("/groupTest")
public Result<String> groupTest() {
List<String> list = List.of("subCategory", "classifyId");
ProjectionOperation count = Aggregation.project("count");
for (String s : list) {
count = count.and("_id." + s).as(s); // 将 _id 中的字段平铺出来
}
count = count.andExclude("_id");
Aggregation aggregation = Aggregation.newAggregation(
// $group 阶段: 按 subCategory 和 classifyId 分组,并计算每个分组的数量
Aggregation.group("subCategory", "classifyId")
.count().as("count"),count
);
// Step 2: 执行聚合操作
AggregationResults<JSONObject> results = mongoTemplate.aggregate(aggregation, "wf_design", JSONObject.class);
// Step 3: 返回结果
return Result.ofSuccess(results.getMappedResults().toString());
}
ProjectionOperation:对返回字段进行处理,动态构建时需重新赋值,避免字段映射不上