Spring mongoTemplate时间戳分组统计
•编程
894
0
需求描述:按天统计每天的数量
_id、action、successed、createTime(毫秒时间戳)
db.user_action_log.aggregate([
// 查询条件
{ $match: { createTime:{ $gte: 1635042445000, $lte: 1640311312000} } },
// 将时间戳转为日期
{ $project: { day: { $dateToString: { format: '%Y-%m-%d', date: {'$add':[new Date(0),'$createTime']}, timezone: 'Asia/Shanghai' } } } },
// 分组统计
{ $group: { _id: '$day', count: { $sum: 1 } } },
// 指定输出字段
{ $project: { label: '$_id', count: '$count', _id: 0 } },
{ $sort: { 'label': 1 } }
])
List<AggregationOperation> operations = new ArrayList<>();
// 查询条件
Criteria criteria = Criteria.where("createTime").gte(startTime).lte(endTime);
operations.add(Aggregation.match(criteria));
// 将时间戳转为时间
operations.add(
Aggregation
.project("createTime")
.andExpression("{$dateToString: {date: { $add: {'$createTime', [0]} }, format: '%Y-%m-%d', timezone: 'Asia/Shanghai' }}", new Date(0))
.as("day")
);
// 分组统计
operations.add(Aggregation.group("day").count().as("count"));
// 输出字段
operations.add(Aggregation.project("day", "count").and("label").previousOperation());
// 排序
operations.add(Aggregation.sort(Sort.Direction.ASC, "label"));
// 执行
AggregationResults<GroupCount> result = mongoTemplate.aggregate(Aggregation.newAggregation (operations), "u_user_action_log", GroupCount.class);
return result.getMappedResults();