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")
        // 添加其他需要返回的字段
);
相关推荐
橘猫云计算机设计1 小时前
基于Springboot的自习室预约系统的设计与实现(源码+lw+部署文档+讲解),源码可白嫖!
java·spring boot·后端·毕业设计
秋书一叶2 小时前
SpringBoot项目打包为window安装包
java·spring boot·后端
碎梦归途2 小时前
23种设计模式-结构型模式之外观模式(Java版本)
java·开发语言·jvm·设计模式·intellij-idea·外观模式
极客先躯2 小时前
高级java每日一道面试题-2025年4月13日-微服务篇[Nacos篇]-Nacos如何处理网络分区情况下的服务可用性问题?
java·服务器·网络·微服务·nacos·高级面试
pwzs3 小时前
Spring MVC 执行流程全解析:从请求到响应的七步走
java·后端·spring·spring mvc
我该如何取个名字3 小时前
Mac配置Java的环境变量
java·开发语言·macos
kkkkatoq3 小时前
Java中的锁
java·开发语言
界面开发小八哥4 小时前
「Java EE开发指南」用MyEclipse开发EJB 3无状态会话Bean(二)
java·ide·java-ee·eclipse·myeclipse
LCY1334 小时前
spring security +kotlin 实现oauth2.0 认证
java·spring·kotlin
soulermax4 小时前
数字ic后端设计从入门到精通2(含fusion compiler, tcl教学)
java·linux·服务器