栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

mongo-Aggregation聚合查询踩坑

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

mongo-Aggregation聚合查询踩坑

目的:

按天对数据进行分组

问题:

一开始的写法如下(简写,凸显问题),聚合查出的数据都为空,数量为零

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 results = mongoTemplate.aggregate(aggregation, MONGO_TABLE_NAME, Map.class);
results.getMappedResults().forEach(System.out::println);
List 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 results = mongoTemplate.aggregate(aggregation, MONGO_TABLE_NAME, Map.class);
results.getMappedResults().forEach(System.out::println);
List 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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/281456.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号