Java连接MongoDB管道查询慢 记录解决过程

时间:2024-05-22 18:00:53

项目数据列表上万条后用聚合查询aggregat已经无法达到快速查询的效果,管道操作因为unwind和group也会过滤掉索引,连表查询对索引也会失效,经验不足的我苦思许久都找不到解决办法,贴一段代码如下:

private List<AggregationOperation> getBaseAggregateOperation() {
        List<AggregationOperation> aggregations = new ArrayList<>();
        aggregations.add(Aggregation.lookup("t_device_info", "s_device_id", "_id", "deviceInfo"));
        aggregations.add(Aggregation.unwind("deviceInfo"));
        aggregations.add(Aggregation.lookup("t_device_type", "deviceInfo.i_type_id", "_id", "deviceType"));
        aggregations.add(Aggregation.unwind("deviceType"));
        aggregations.add(Aggregation.lookup("t_house_hold", "deviceInfo.s_household_id", "_id", "household"));
        aggregations.add(Aggregation.unwind("household"));
        return aggregations;
    }

如图主表连接其他表三次,然后进行unwind,换成数据库脚本操作查询1w数据也要3s,更不要说加上之后分页,条件查询,sort等一系列操作。客户明显无法接受如此速度,翻遍了百度谷歌,也找不到好的解决办法,ps:因为传统分页以及客户需求,必须要统计分页count,于是乎需要一条条的统计。

最终的缓兵之计是先将多表查询用单表一次次的查询结果,贴一张个人思路图,
Java连接MongoDB管道查询慢 记录解决过程

  • 目前我先将主表数据查询出来然后用主表对应其他表的id去查其他表,4张表以此查询出来,但是对于N:1,无法正确查询出想要的结果,存到一个对象中。我想要达成的为通过单表查询4次数据库,然后得到想要的结果集,最后对结果集进行分页以及一系列操作,因为单表查询可以速度很快,也可以加索引优化
  • 未完待续