mongTemplate实现group分组查询aggregation

MongoService封装

java 复制代码
<T> List<T> group(Class<T> clazz, Aggregation aggregation,String documentName);

MongoServiceImpl实现类

java 复制代码
@Override
	public <T> List<T> group(Class<T> clazz, Aggregation aggregation,String documentName) {
		// 执行聚合查询
		//aggegation:所有条件的封装 , CTL_HEART_BEAT:集合/表 ,DeviceGroupByResult.class:接收数据对象
		AggregationResults<T> aggregate = mongoTemplate.aggregate(aggregation, documentName, clazz);
		//这里就很友好了
		return aggregate.getMappedResults();

	}

实践

java 复制代码
             // 构建聚合查询
                Aggregation aggregation = Aggregation.newAggregation(
                        Aggregation.match(Criteria.where("_id").ne(null)),
                        Aggregation.group("otel_id")
                                .first("otel_id").as("otel_id")
                                .first("nel_id").as("nel_id")

                );
                List<Price> priceList = mongoService.group(Price.class, aggregation, "min_price");
                

注意管道的分组

java 复制代码
在给定的聚合管道中,$group 阶段指定了 _id 字段作为分组依据,而且使用了 $otel_id 作为它的值。这意味着分组的结果将以 otel_id 字段的值作为分组的标识符。

因此,在 $group 阶段的结果中,会产生一个 _id 字段,其值与原始文档中的 otel_id 字段的值相对应。换句话说,_id 字段是用于表示分组的唯一标识符,而不再保持原始字段名。

使用真正的字段映射

java 复制代码
Aggregation aggregation = Aggregation.newAggregation(
    Aggregation.match(Criteria.where("otel_id").ne(null)),
    Aggregation.group("otel_id")
        .count().as("count")
        .first("field1").as("field1")
        .first("field2").as("field2")
        .first("field3").as("field3")
        // 添加其他需要返回的字段
);
相关推荐
LUCIAZZZ1 分钟前
JVM之内存管理(一)
java·jvm·spring·操作系统·springboot
D_aniel_17 分钟前
排序算法-计数排序
java·排序算法·计数排序
极小狐23 分钟前
极狐GitLab 通用软件包存储库功能介绍
java·数据库·c#·gitlab·maven
旧故新长35 分钟前
Browserless 快速上手
java
java1234_小锋41 分钟前
Spring Bean有哪几种配置方式?
java·后端·spring
?abc!42 分钟前
缓存(5):常见 缓存数据淘汰算法/缓存清空策略
java·算法·缓存
DanB241 小时前
Java笔记4
java·开发语言·笔记
Dddle11 小时前
C++:this指针
java·c语言·开发语言·c++
阿乾之铭2 小时前
Spring Boot 参数验证
java·数据库·mysql
佩奇的技术笔记2 小时前
Java学习手册:微服务设计原则
java·微服务