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