MongoError: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.
Post

MongoError: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.

MongoError: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.

원인

해당 예외는 mongodb가 검색 및 정렬 쿼리 시 메모리를 32MB 초과 사용시 나타나는 오류이다.

해결 방법

아래의 방법 대로 순차적으로 시도해본다.

  1. 검색 및 정렬 시 사용하는 필드를 인덱스 생성해 준다.
  2. find() 대신 aggregate()를 사용한다.
  3. 메모리 공간을 크게 설정한다.

1.인덱스 조회 및 생성

1
2
3
> db.COLLECTION.getIndexes() # 인덱스 조회
> db.COLLECTION.createIndex({ FIELD: 1 }) # 인덱스 생성: 1은 오름차순, -1은 내림차순 정렬
> db.COLLECTION.createIndex({ FIELD1: 1, FIELD2: -1 }) # 복합 인덱스 생성

2.aggregate 사용

find() 대신 aggregate()를 사용하고 allowDiskUse 옵션을 true로 설정한다.

1
2
3
> db.COLLECTION.find({FIELD1: true}).sort({FIELD2: 1}) # find 예시

> db.COLLECTION.aggregate([{$match: {FIELD1: true}}, {$sort: {FIELD2: 1}}], {allowDiskUse:true}) # aggregate 예시

3.메모리 공간 크게 설정

admin 으로 변경하여 현재 용량 조회 및 변경을 해준다. 기본값은 32MB(33554432바이트)이다.

1
2
3
4
5
6
7
> use admin # admin으로 변경 

> db.runCommand({ getParameter : 1, "internalQueryExecMaxBlockingSortBytes" : 1 }) # 현재 용량 조회
{ "internalQueryExecMaxBlockingSortBytes" : 33554432, "ok" : 1 }

> db.adminCommand({ setParameter: 1, internalQueryExecMaxBlockingSortBytes:50151432}) # 50MB로 용량 늘리기 
{ "was" : 33554432, "ok" : 1 }