目的:
按天对数据进行分组
问题:
一开始的写法如下(简写,凸显问题),聚合查出的数据都为空,数量为零
String startTime = "2021-08-30 00:00:00";
String endTime = "2021-09-30 00:00:00";
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.project("sTime").andExpression("substr(sTime,0,10)").as("day"),
Aggregation.match(Criteria.where("sId").is(1)
.and("sTime").gte(startTime).lt(endTime)),
Aggregation.group("day")
);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, MONGO_TABLE_NAME, Map.class);
results.getMappedResults().forEach(System.out::println);
List<Map> mapList = results.getMappedResults();
System.out.println("数量:"+mapList.size());
修改为如下代码解决:
String startTime = "2021-08-30 00:00:00";
String endTime = "2021-09-30 00:00:00";
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("sId").is(1)
.and("sTime").gte(startTime).lt(endTime)),
//将.project() 放到 .match() 条件后
Aggregation.project("sTime").andExpression("substr(sTime,0,10)").as("day"),
Aggregation.group("day")
);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, MONGO_TABLE_NAME, Map.class);
results.getMappedResults().forEach(System.out::println);
List<Map> mapList = results.getMappedResults();
System.out.println("数量:"+mapList.size());
解释:
- mongo没有像mysql一样存在子查询的概念
- mongo有管道的概念,也可以把管道理解成mysql中子查询
- Aggregation相当于一个管道,需要从上至下将处理结果传递下去,如果直接将project放到match前边后,project中需要的sTime参数将得不到赋值,通过打印的mongo语句可以看到sTime=1(这个应该是未知参数的默认值),所以导致每次查询都为空
其他:
打印mongo语句日志,配置文件中添加如下配置:
logging.level.org .springframework.data.mongodb.core= DEBUG