MongoDB使用聚合Aggregation
↓↓
↓↓
↓↓
正文
//查询近30天上传数据
Map<String, Object> map = new HashMap();
//当前时间
Date now = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(now);
// 将当前时间减30就是一月前,一月后写30即可
cal.add(java.util.Calendar.DAY_OF_MONTH, -30);
//cal.getTime();//一个月前的时间
List<Long> sizeList = new ArrayList<Long>();
Map<String, Object> logMap = new HashMap<String, Object>();
Aggregation aggregation4 =
Aggregation.newAggregation(
//Aggregation.match(Criteria.where("uploadDate").lte(now)),
//Aggregation.match(Criteria.where("uploadDate").gte(cal.getTime())),
Aggregation.project().andExpression("{$dateToString:{ format:'%Y-%m-%d',date: '$uploadDate'}}").as("Day").andExpression("$length").as("length"),
//Aggregation.project("uploadDate").andExpression("Y-%m-%d").as("dateTime").and("length").as("length"),
Aggregation.group("Day").first("Day").as("time").sum("length").as("size"),
Aggregation.sort(Sort.Direction.DESC, "time"));
//Aggregation.project().andExpression("{$_id.time}").as("Day").andExpression("$size").as("Size"));
AggregationResults<Map> aggregate = mongoTemplate.aggregate(aggregation4, collectionName, Map.class);
//流量集合
List<Map> flowList = aggregate.getMappedResults();
Date endTime = new Date();
Calendar begin = Calendar.getInstance();// 得到一个Calendar的实例
begin.setTime(endTime); // 设置时间为当前时间
begin.add(Calendar.MONTH, -1);// 月份减1
begin.add(Calendar.DATE, +1);// 日期加1
Date startTime = begin.getTime();
List<String> timeList = TimeUtils.getTimeList(startTime, endTime);
String time;
//赋值
for (int i = 0; i < timeList.size(); i++) {
time = timeList.get(i);
sizeList.add(i, 0L);
for (Map flowMap : flowList) {
if (time.equals(flowMap.get("time"))) {
sizeList.set(i, (Long) flowMap.get("size"));
break;
}
}
}
map.put("timeList", timeList);
map.put("sizeList", sizeList);