使用Mongoose聚合排序触发内存限制错误,allowDiskUse(true)无效求助
解决Mongoose聚合排序内存超限问题
1. 修正allowDiskUse调用方式
部分Mongoose版本中,链式调用.allowDiskUse(true)可能不生效,改为将allowDiskUse作为配置选项传入aggregate方法:
Model.aggregate([ { $lookup: { from: 'collection', localField: '_id', foreignField: 'ref', as: 'other' } }, { $set: { other: { $arrayElemAt: ['$other', 0] } } }, { $sort: { 'something': 1 } }, { $skip: 50000 }, { $limit: 100 }, ], { allowDiskUse: true }).then((results) => { console.log(results); });
若使用较新版本Mongoose,也可确保链式调用在exec()前执行(兼容then链式写法):
Model.aggregate([/* 聚合阶段 */]) .allowDiskUse(true) .exec() .then(results => console.log(results));
2. 优化聚合阶段顺序(推荐)
当前排序在关联操作之后,会导致排序时处理的是关联后的大体积数据,更容易触发内存限制。调整顺序,先排序、分页,再执行关联,大幅减少排序处理的数据量:
Model.aggregate([ { $sort: { 'something': 1 } }, { $skip: 50000 }, { $limit: 100 }, { $lookup: { from: 'collection', localField: '_id', foreignField: 'ref', as: 'other' } }, { $set: { other: { $arrayElemAt: ['$other', 0] } } }, ], { allowDiskUse: true }).then(results => { console.log(results); });
3. 给排序字段创建索引
为something字段创建单字段索引,MongoDB会利用索引直接生成有序结果,无需将全量数据加载到内存排序,从根源避免内存超限问题:
// 在Model定义中添加索引 Model.index({ something: 1 }); // 或直接在MongoDB Shell中执行 db.models.createIndex({ something: 1 });
内容的提问来源于stack exchange,提问作者Elyas Behroozizade
相关产品推荐
相关产品推荐

