Spring 中 MongoDb 的“排序超出内存限制”问题

Ped*_*que 6 java database criteria mongodb spring-boot

我正在编写一个方法来使用 MongoRepository 实现查询,我在 Java/Spring 项目中使用聚合,但在测试时它超出了内存限制。

我尝试过使用

newAggregationOptions().cursorBatchSize(pageable.getPageSize()).allowDiskUse(true).build()
Run Code Online (Sandbox Code Playgroud)

但没有用

我的方法:

...
        var matchCriteria = match(criteria);

        var unwindVariations = unwind("variations", false);


        var sort = sort(Sort.Direction.ASC, "variations.plataformStatus.status");

        var countResult = count().as("totalElements");
        var aggregationOptions = Aggregation.newAggregationOptions().cursorBatchSize(pageable.getPageSize()).allowDiskUse(true).build();

        var countAggregation = newAggregation(
                matchCriteria,
                unwindVariations,
                sort,
                countResult)
                .withOptions(aggregationOptions);

        var totalElements = mongoTemplate.aggregate(countAggregation, "PRODUCT", Map.class).getMappedResults();


Run Code Online (Sandbox Code Playgroud)

错误信息:

com.mongodb.MongoCommandException: Command failed with error 16819 (Location16819): 'Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting. Aborting operation. Pass allowDiskUse:true to opt in.' on server cluster0-shard-00-01-du380.mongodb.net:27017.
Run Code Online (Sandbox Code Playgroud)

Gon*_*heu 2

您应该启用allowDiskUse选项。

默认情况下,排序操作有 100MB 限制(在内存中),在操作中启用该选项将允许使用更大的大小。

来自MongoDB 的排序文档

$sort 阶段的 RAM 限制为 100 MB。默认情况下,如果阶段超过此限制,$sort 将产生错误。要允许处理大型数据集,请将 allowedDiskUse 选项设置为 true 以使 $sort 操作能够写入临时文件。