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")
        // 添加其他需要返回的字段
);
相关推荐
极客先躯10 分钟前
说说高级java每日一道面试题-2025年2月13日-数据库篇-请说说 MySQL 数据库的锁 ?
java·数据库·mysql·数据库的锁·模式分·粒度分·属性分
程序员侠客行13 分钟前
Spring事务原理 二
java·后端·spring
小猫猫猫◍˃ᵕ˂◍28 分钟前
备忘录模式:快速恢复原始数据
android·java·备忘录模式
liuyuzhongcc36 分钟前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list
五月茶40 分钟前
Spring MVC
java·spring·mvc
sjsjsbbsbsn1 小时前
Spring Boot定时任务原理
java·spring boot·后端
yqcoder1 小时前
Express + MongoDB 实现在筛选时间段中用户名的模糊查询
java·前端·javascript
jiugie1 小时前
MongoDB学习
数据库·python·mongodb
hzulwy1 小时前
MongoDB应用设计调优
数据库·mongodb
菜鸟蹦迪1 小时前
八股文实战之JUC:ArrayList不安全性
java