Executor error during find command: OperationFailed: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.

栏目: mongoose教程 发布时间:2023-01-11

mongoose 出现如下报错:

Executor error during find command: OperationFailed: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.

报错信息翻译成中文如下:

执行器在执行 find 命令期间发生错误了:OperationFailed:排序操作使用的RAM超过了最大 33554432 字节。添加索引或指定较小的 limit。

33554432 字节也就是 32Mb。mongodb 的 sort 操作是在内存中进行排序的,sort 操作默认限制了最大内存为 32Mb,当数据量超过 32Mb 的时候就报错了。

上述报错信息其实已经指明了 2 种解决方案:

  • 1、添加索引

以 mongoose 为例,可以在 Schema 中为参与排序的字段创建索引

const dayjs = require('dayjs')
module.exports = app => {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;

  const ArticleSchema = new Schema({
    ...
    createdTime: {
      type: Date,
      default: new Date(),
      get: v => dayjs(v).format('YYYY-MM-DD'),
      // 创建索引
      index: true,
    },
    ...
  });
  return mongoose.model('Article', ArticleSchema);
}
  • 2、减小 limit

比如将查询的 limit 由 10000 调整为 1000

本文地址:https://www.tides.cn/p_mongoose-sort-operation-used-more-than-the-maximum-33554432-bytes-of-ram