1.数据集合如下所示
{
"_id" : ObjectId("61b0ba42ad73bc04fc538bdq”),
"userId" : "61af93b3ad73bc04fc538b21”,
“schoolName”:”北京大学”,
"status" : 1,
"createTime" : ISODate("2021-12-08T13:59:20.495Z"),
"updateTime" : ISODate("2021-12-08T14:44:16.213Z"),
"delete" : false
}
需求:学校分布
//需要展示的字段
ProjectionOperation project = Aggregation.project("schoolName", "total")
// 格式化时间
.andExpression("{$dateToString:{format:'%Y-%m-%d',date:'$createTime',timezone: 'Asia/Shanghai'}}").as("createTime");
//根据schoolName字段分组求和
GroupOperation group = Aggregation.group("schoolName").count().as("total").last("schoolName").as("schoolName");
//构造条件
Criteria criteria = new Criteria();
if(StringUtils.isNotBlank(school.getStartTime()) && StringUtils.isNotBlank(school.getEndTime())){
//根据日期做范围查找
criteria = Criteria.where("createTime").gte(DateUtils.dateToISODate(clockIn.getStartTime()+" 00:00:00")).lte(DateUtils.dateToISODate(clockIn.getEndTime()+" 23:59:59"));
}
MatchOperation match = Aggregation.match(criteria);
Aggregation agg = Aggregation.newAggregation(match,project,group,
Aggregation.skip((pageRequest.getPageNumber()) * pageRequest.getPageSize()),//跳到第几个开始
Aggregation.limit(pageRequest.getPageSize())//查出多少个数据
);
AggregationResults<Map> aggregate = this.aggregate(agg, “school”, Map.class);
List<Map> mappedResults = aggregate.getMappedResults();
2.数据集合
{
"_id" : ObjectId("61b0ba42ad73bc04fc538bdq”),
"userId" : "61af93b3ad73bc04fc538b21”,
"status" : 1,
"userInfo" : {
"name" : "刘元”,
“age” : "22”,
"sex" : "男"
},
"createTime" : ISODate("2021-12-08T13:59:20.495Z"),
"updateTime" : ISODate("2021-12-08T14:44:16.213Z"),
"delete" : false
}
2.求性别分布
//需要展示的字段
ProjectionOperation project = Aggregation.project("total","sex")
//给要分组的字段userInfo.sex起一个别名位sex
.andExpression("userInfo.sex").as(sex");
//根据别名sex分组
GroupOperation group = Aggregation.group(sex").count().as("total")
.last(sex").as(sex");
//条件
Criteria criteria = Criteria.where("status").is(“1”);
MatchOperation match = Aggregation.match(criteria);
//根据分组求出的数据顺序倒叙排列
SortOperation sort = Aggregation.sort(new Sort(Sort.Direction.DESC, "total"));
Aggregation agg = Aggregation.newAggregation(match,project,group,sort,
//查出多少个数据
Aggregation.limit(10)
);
AggregationResults<Map> aggregate = this.aggregate(agg,"school", Map.class);
List<Map> mappedResults = aggregate.getMappedResults();
参考博客:spring-boot使用mongoDB的聚合查询,mongoDB分组查询(group)Aggregation,以及查询不固定表的数据_鹏的博客-CSDN博客