springboot + mongodb 聚合查询

springboot mongodb 聚合查询

​ 啊这,这次没有前言。

版本 :

  • springboot 2.3.4
  • mongodb-driver 4.0.5

maven 依赖 :

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

MongoTestPo :

@Data
@ToString
@EqualsAndHashCode(callSuper = false)
public class MongoTestPo implements Serializable {
    private static final long serialVersionUID = 464912482412264843L;
    private String id;
    private String testCode;
    private String testName;
    private String startTime;
    private String endTime;
    private Integer gender;
    private Integer age;
    private Integer minAge;
    private Integer maxAge;
    private Integer avgAge;
    private Integer count;
}

普通查询 :

// startTime <= start_time < endTime
// gender = 1
// test_code in ('qqqq', 'wwww')
// .find(Query query, Class<T> entryClass, String collectionName)
List<MongoTestPo> list = mongoTemplate.find(new Query(Criteria.where("start_time")
                .gte(startTime.toEpochSecond(ZoneOffset.of("+8")))
                .lt(endTime.toEpochSecond(ZoneOffset.of("+8")))
                .and("gender").is(1)
                .and("test_code").in("qqqq", "wwww")), MongoTestPo.class, "collection_one");

聚合查询 :

// springboot mongo 中的聚合类(两个集合: collection_one, collection_two)
Aggregation aggregation = Aggregation.newAggregation(
    
    // 需要查询的列以及查询过程中用到的列
    Aggregation.project("test_code", "detail.test_name", "start_time", 
                        "end_time", "age", "gender"),
    
    // 匹配条件
    Aggregation.match(Criteria.where("start_time")
                      .gte(startTime.toEpochSecond(ZoneOffset.of("+8")))
                      .lt(endTime.toEpochSecond(ZoneOffset.of("+8")))
                      .and("gender").is(1)
                      .and("test_code").in("qqqq", "wwww")),
    
    // 关联查询
    // .lookup(String fromCollectionName, String localFeild, String foreginFeild, String as)
    // 关联集合名称、主表关联字段、从表关联字段、别名
    Aggregation.lookup("collection_two", "test_code", "test_code", "detail"),
    
    // 分组查询
    // .first()、.last()、.min()、max()、.avg()、.count() 后需调用 .as() 对结果值进行重命名
    Aggregation.group("test_code")   // 分组条件
    .first("test_code").as("test_code")   // 获取分组后查询到的该字段的第一个值
    .first("detail.test_name").as("test_name")
    .sum("age").as("age")   // 按分组对该字段求和
    .min("age").as("min_age")   // 按分组求该字段最小值
    .max("age").as("max_age")   // 按分组求该字段最大值
    .avg("age").as("avg_age")   // 按分组求该字段平均值
    .first("start_time").as("start_time")
    .last("end_time").as("end_time")   // 获取分组后查询到的该字段的最后一个值
    .first("gender").as("gender")
    .count().as("count"),   // 统计分组后组内条数
    
    Aggregation.sort(Sort.Direction.DESC, "avg_age"),   // 排序
    
    Aggregation.skip(0L),   // 分页
    Aggregation.limit(10L),
    
    // 输出的列
    Aggregation.project("test_code", "test_name", "start_time", "end_time", "age", 
                        "min_age", "max_age", "avg_age", "gender", "count")
);

// .aggregation(Aggregation aggregation, String collectionName, Class<T> entryClass)
AggregationResults<MongoTestPo> results = 
    	mongoTemplate.aggregate(aggregation, "collection_one", MongoTestPo.class);
// 获取结果集
List<MongoTestPo> list = results.getMappedResults();

@XGLLHZ-《人来人往》.mp3-陈奕迅

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SpringBoot中集成MongoDB的管道聚合可以通过使用聚合管道(Aggregation Pipeline)来实现。聚合管道是MongoDB提供的一种强大的数据处理工具,可以对数据进行多个阶段的处理和转换。 在SpringBoot项目中使用聚合管道,首先需要引入MongoDB的依赖,并配置MongoDB的连接信息。在yml配置文件中,可以使用以下格式配置MongoDB的URI: ``` spring: data: mongodb: uri: mongodb://用户名:密码@127.0.0.1:port/库名?authSource=admin&authMechanism=SCRAM-SHA-1 ``` 其中,用户名、密码、IP地址、端口号、库名等信息需要根据实际情况进行替换。 接下来,在服务层的代码中,可以使用MongoTemplate或MongoOperations来执行聚合管道操作。聚合管道可以包含多个阶段,每个阶段都是一个操作,可以对数据进行筛选、排序、分组、计算等操作。 例如,可以使用聚合管道来实现对某个集合中的数据进行分组统计: ```java Aggregation aggregation = Aggregation.newAggregation( Aggregation.group("字段名").count().as("统计结果") ); AggregationResults<统计结果类型> results = mongoTemplate.aggregate(aggregation, "集合名", 统计结果类型.class); List<统计结果类型> resultList = results.getMappedResults(); ``` 其中,字段名是需要进行分组统计的字段,统计结果是统计的结果字段名。集合名是需要进行聚合操作的集合名称,统计结果类型是自定义的结果类型。 通过以上方式,可以在SpringBoot项目中使用MongoDB的管道聚合功能进行数据统计和处理。\[2\]\[3\] #### 引用[.reference_title] - *1* *2* *3* [SpringBoot集成MongoDB(2)|(中级-数据统计、集合、管道处理)](https://blog.csdn.net/Oaklkm/article/details/125716072)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值