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")
        // 添加其他需要返回的字段
);
相关推荐
架构师沉默几秒前
外卖平台每天1000万订单查询,是如何扛住高并发的?
java·后端·架构
kushu734 分钟前
Java 包
java·开发语言
bug菌1 小时前
🤔领导突然考我Spring中的注解@Bean,它是做什么用的?我...
java·后端·spring
JavaArchJourney1 小时前
ArrayList 源码分析
java
寒士obj1 小时前
熟悉并使用Spring框架 - 注解篇
java·spring
BricheersZ2 小时前
LangChain4J-(1)-Hello World
java·人工智能·langchain
回家路上绕了弯2 小时前
Spring ApplicationContext 源码深度剖析:容器的核心引擎
java·spring
心月狐的流火号2 小时前
线程池ThreadPoolExecutor源码分析(JDK 17)
java·源码阅读
AAA修煤气灶刘哥2 小时前
手把手教你Mybatis-Plus :小白看完都能会,看完还不回找我,我给你补个蛋
java·后端
悦人楼2 小时前
当C#遇上Notepad++:实现GCode可视化编辑的跨界实践
java·c#·notepad++