MongoDB 使用排序内存不足解决方法

问题
解决

1.问题原因

最近在使用mongoDB大批量数据查询时遇到问题,但在查询数据并且排序展示时MongoDB直接抛出了异常

"ok": 0.0, "errmsg": "Sort exceeded memory limit of 104857600 bytes,
 but did not opt in to external sorting. Aborting operation. Pass allowDiskUse:true to opt in.", "code": 16819

大概意思就是MongoDB在进行排序查询时超出了内存限制100M,可以使用allowDiskUse来进行系统缓存将数据写入临时文件以进行排序

2.解决方法

  1. 首先是在mongoDB查询中使用allowDiskUse=true来开启
-- 原始语句
db.collectionName.aggregate([{
    $project: {
        field1: 1,
        field2:1
    }
}, {
    $match: {
        field1: {
            $gte: 3000
        }
    }
}, {
    $sort: {
        field2: - 1
    }
}])


-- 开启allowDiskUse
db.collectionName.aggregate([{
    $project: {
        field1: 1,
        field2:1
    }
}, {
    $match: {
        field1: {
            $gte: 3000
        }
    }
}, {
    $sort: {
        field2: - 1
    }
}], {
    allowDiskUse: true
})
  1. 在java代码里来实现
//AggregationOptions里开启allowDiskUse
Cursor cdaDoclist = mongoTemplate.getCollection("collectionName").aggregate(pipeLine, AggregationOptions.builder().allowDiskUse(true).outputMode(AggregationOptions.OutputMode.CURSOR).build());
//获取查询结果集Cursor对象
while (cdaDoclist.hasNext()){
    cdalist.add(cdaDoclist.next());
}
  • 学习记录仅供参考