springboot mongdb 聚合操作记录

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博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值