MongoDB:
先查出来数据库的数据
TypedAggregation<ImageInfo> agg = Aggregation.newAggregation(ImageInfo.class,
Aggregation.match(criteria),
Aggregation.project("addDate").andExpression("{ $dateToString: {date: '$addDate', format: '%Y-%m-%d', timezone: '+08:00'}}").as("date"),
Aggregation.group("date").count().as("value"),
//排序应为升序,与dateList(小到大)照应
Aggregation.sort(new Sort(Direction.ASC, "_id")));
CloseableIterator<Document> r = mongoTemplate.aggregateStream(agg, Document.class);
while(r.hasNext()){
Document d = r.next();
Document doc = new Document("name", d.get("_id")).append("value", d.getInteger("value"));
list.add(doc);
}
查出来数据库中最大最小日期,调用补充日期方法:
Date maxDate = mongoTemplate.findOne(new Query().with(new Sort(Direction.DESC, "addDate")), ImageInfo.class).getAddDate();
Date minDate = mongoTemplate.findOne(new Query().with(new Sort(Direction.ASC, "addDate")), ImageInfo.class).getAddDate();
List<Date> dateList = FileUtil.dateList(minDate, maxDate);
this.dateFullList(dateList, list);
补充日期方法:
/**
* 补充日期序列
* @param dateList:日期列表
* @param list:要补充的日期列表
* @return
*/
private List<Document> dateFullList(List<Date> dateList, List<Document> list){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
boolean exist=false;
for (int i = 0; i < dateList.size(); i++) {
exist=false;
for (int j = 0; j < list.size(); j++) {
if(list.get(j).get("name").toString().equals(sdf.format(dateList.get(i)))){
exist=true;
break;
}
}
if (!exist){
Document doc = new Document();
doc.append("name", sdf.format(dateList.get(i))).append("value", 0);
list.add(i,doc);
}
}
return list;
}
结果分析:
数据库查出来的数据:
Document{{name=2019-09-16, value=341}}
Document{{name=2019-09-17, value=40}}
Document{{name=2019-09-18, value=6}}
Document{{name=2019-09-19, value=10}}
Document{{name=2019-09-20, value=12}}
Document{{name=2019-09-23, value=12}}
Document{{name=2019-09-24, value=81}}
经过方法补充日期,得到的想要数据:
Document{{name=2019-09-16, value=341}}
Document{{name=2019-09-17, value=40}}
Document{{name=2019-09-18, value=6}}
Document{{name=2019-09-19, value=10}}
Document{{name=2019-09-20, value=12}}
Document{{name=2019-09-21, value=0}}
Document{{name=2019-09-22, value=0}}
Document{{name=2019-09-23, value=12}}
Document{{name=2019-09-24, value=81}}
Document{{name=2019-09-25, value=0}}
结果完美实现预期目的。