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")
        // 添加其他需要返回的字段
);
相关推荐
期待のcode5 小时前
Java的反射
java·开发语言
2201_757830876 小时前
AOP入门程序
java·开发语言
雨中飘荡的记忆6 小时前
MyBatis反射模块详解
java·mybatis
宸津-代码粉碎机6 小时前
Spring 6.0+Boot 3.0实战避坑全指南:5大类高频问题与解决方案(附代码示例)
java·数据仓库·hive·hadoop·python·技术文档编写
笃行客从不躺平6 小时前
ThreadLocal 复习一
java·开发语言
程序帝国6 小时前
SpringBoot整合RediSearch(完整,详细,连接池版本)
java·spring boot·redis·后端·redisearch
安卓程序员_谢伟光6 小时前
如何监听System.exit(0)的调用栈
java·服务器·前端
Pluto_CSND6 小时前
JSONPath解析JSON数据结构
java·数据结构·json
xiaoliuliu123456 小时前
Tomcat Connectors 1.2.32 源码编译安装教程(含 mod_jk 配置步骤)
java·tomcat
CYTElena6 小时前
JAVA关于集合的笔记
java·开发语言·笔记