springboot + mongodb 聚合查询

本文详细介绍了如何在SpringBoot项目中使用MongoDB的聚合操作进行复杂查询。通过示例展示了如何进行匹配、投影、关联、分组、排序、跳过和限制等步骤,实现对数据的高效检索和分析。同时,代码示例中还包含了查询条件的设置,如时间范围、性别过滤和特定字段的值筛选。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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-陈奕迅

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值