java mongoTemplate时间戳格式化,分组聚合查询

用于接收返回数据的对象
(直接用一个Map<String,Object>接收也可以)

private int count;
private String date;

查询7天内的eventType的数据,并按日期聚合查询:

		//当前时间
		Date time = new Date();
		//7天前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.HOUR_OF_DAY, -7 * 24);

        Aggregation aggregation = Aggregation.newAggregation(
        		//时间范围
                Aggregation.match(Criteria.where("createTime").gt(calendar.getTime().getTime())),
                Aggregation.match(Criteria.where("createTime").lt(time.getTime())),
                //where条件
                Aggregation.match(Criteria.where("eventType").is(eventType)),
                //将时间戳格式化并重命名
                Aggregation.project("createTime").andExpression("{$dateToString: {date: { $add: {'$createTime', [0]} }, format: '%Y-%m-%d'}}", new Date(28800000)).as("day"),
                //分组统计
                Aggregation.group("day").count().as("count"),
                //如果不加这条,输出的结果如: [{"count": 3, "_id": "2019-12-13"}]
                //加上为:				   [{"count": 3, "date": "2019-12-13"}]
                Aggregation.project("day", "count").and("date").previousOperation(),
                //排序
                Aggregation.sort(Sort.Direction.ASC, "date"));

        AggregationResults<FindPhoneClientEcharVO> result = mongoTemplate.aggregate(aggregation, ClientEventLoginfo.class, FindPhoneClientEcharVO.class);
        List<FindPhoneClientEcharVO> list = result.getMappedResults();

这方面的资料本身较少.加上业务不同,花了一个早上的时间才得出想要的结果.

参考自:https://blog.csdn.net/lMasterSparkl/article/details/109679841
https://blog.csdn.net/sinat_30735061/article/details/103520437

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值