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

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

  1. 问题
  2. 解决

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());
}
  • 学习记录仅供参考
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值