mongodb 查询大量数据 速度慢的问题?

新手上路,请多包涵

一开始使用mongoTemplate 进行查询表数据为19万数据,查询结果数据大约4万条数据,耗时40 秒,添加索引后耗时20秒,但还是觉得太慢了,然后查看帖子建议不使用mongoTemplate,转而使用cursor 也就是游标的方式进行查询最后得出的代码为:

 Bson filter = Filters.gte("forecastdate", date);
        CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
                MongoClientSettings.getDefaultCodecRegistry(),
                CodecRegistries.fromProviders(new StatisticsDetailDaoCodecProvider())
        );
        List<StatisticsDetailDao> allDetail = new ArrayList<>();
        MongoCursor<StatisticsDetailDao> cursor = mongoTemplate.getDb().getCollection("STRATEGY_STATISTICS_DETAIL", StatisticsDetailDao.class).withCodecRegistry(codecRegistry).find(filter).cursor();
        try {

            while (cursor.hasNext()) {
                allDetail.add(cursor.next());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

改用了cursor 来进行数据的遍历,但最后结果发现耗时还是20s,并没有啥子大的改变
问题是出现在


            while (cursor.hasNext()) {
                allDetail.add(cursor.next());
            }

这个位置,每次获取到一批数据之后要等好久,才会再次返回,有什么好的方法可以提升查询的速度吗?

阅读 8.7k
2 个回答

一次查这么多数据是要做什么?
数据量大的话查询速度是一方面,数据库和应用之间的网络带宽也会有问题,因为要传输的数据太多了

有一个默认的batchsize ,如果数据量大,就调大。当时回导致内存的占用变高,这时也有一个allowDiskxxx的选项。 都在MongoCursor的api里,你可以看看 。然后在试试

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏