1. mongo 按照时间区间 + 年-月分组统计
Date begin = DateUtil.parse(String.valueOf(year) + DAY_OF_MONTH);
Date end = DateUtil.parse(String.valueOf(year + 1) + DAY_OF_MONTH);
List<String> timeList = new ArrayList<>();
for (int i = 0; i < 12; i++) {
DateTime dateTime = DateUtil.offsetMonth(begin, i);
timeList.add(DateUtil.format(dateTime, YEAR_MONTH));
}
Criteria criteria = new Criteria();
criteria.and(MongoFieldsConstants.COLLECT_MONTH).in(timeList);
List<AggregationOperation> operations = new ArrayList<>();
operations.add(Aggregation.project("catalog_id","status","_id","origin_department","theme_id","create_time")
.andExpression("{$dateToString:{ format:'%Y-%m',date: '$create_time', timezone: 'Asia/Shanghai'}}").as("$collectMonth")
.andExpression("{$dateToString:{ format:'%Y',date: '$create_time', timezone: 'Asia/Shanghai'}}").as("$year")
.andExpression("{$dateToString:{ format:'%m',date: '$create_time', timezone: 'Asia/Shanghai'}}").as("$month"));
operations.add(Aggregation.match(criteria));
operations.add(Aggregation.group(MongoFieldsConstants.THEME_ID,MongoFieldsConstants.ORIGIN_DEPARTMENT,MongoFieldsConstants.COLLECT_MONTH)
.count().as(MongoFieldsConstants.ROWS)
.first("year").as("year")
.first("month").as("month"));
Aggregation aggregation = Aggregation.newAggregation(operations);
return mongoTemplate.aggregate(aggregation, Constants.DMS_COLLECTION_NAME_DATA_RESOURCE, DataResVisualDTO.class).getMappedResults();
2. mongo 分页统计
Sort sort = new Sort(Sort.Direction.DESC, "creationDate");
Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("create_time")));
Query query = new Query().with(pageable);
Sort sort = Sort.by(Sort.Direction.ASC, "_id");
Aggregation agg = Aggregation.newAggregation(
Aggregation.group("source_type").count().as("amount"),
Aggregation.sort(sort)
);