根据年月日分组统计:
如果mongo存储时间格式为date类型,则可根据指定时间格式进行分组统计返回,如存储时间为string类型,则使用mongodb的substr切割函数进行切割日期,按照年月日进行分组统计返回
private List<Document> getReportApi(String collectionName, String type, String
subStrExpress, String startTime, String endTime) {
String subStrExpress = "substr(createTime, 0, 4)";
if ("M".equals(cycle)) {//周期,判断按照年,月,日分组
subStrExpress = "substr(createTime, 0, 7)";
} else if ("D".equals(cycle)) {
subStrExpress = "substr(createTime, 0, 10)";
}
Criteria criteria = new Criteria();
//过滤条件
if (StringUtils.isNoneBlank(type)) {
criteria.and("type").is(type);
}
//筛选时间范围
if (StringUtils.isNoneBlank(startTime) && StringUtils.isNoneBlank(endTime)) {
startTime = startTime + " 00:00:00";
endTime = endTime + " 23:59:59";
criteria.and("createTime").gte(startTime).lte(endTime);
}
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(criteria),
//存储时间格式为date类型,mongoFormat为时间格式 %Y-%m
//Aggregation.project("createTime").
//and(DateOperators.DateToString.dateOf("createTime")
//.toString(mongoFormat)).as("date"),
//存储时间格式为string类型
Aggregation.project().andExpression(subStrExpress).as("date"),
ggregation.group("date").count().as("count"),
//格式化输出为:date,count--原(_id, count)
Aggregation.project("date", "count").and("date").previousOperation(),
//排序
Aggregation.sort(Sort.Direction.ASC, "date")
);
AggregationResults<Document> result = mongoTemplate.aggregate(aggregation,
collectionName, Document.class);
List<Document> documents = result.getMappedResults();
return documents;
}