用于接收返回数据的对象
(直接用一个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