对数据库查出来的日期排序,没有的天数为0

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}}

结果完美实现预期目的。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值