MongoDB - Sort() error - Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.
I'm trying to sort a MongoDB field but i'm getting the below error. How can I handle this?
Error: error: {
"ok" : 0,
"errmsg" : "Executor error during find command :: caused by :: Sort operation used more than the maximum 33554432 bytes of RAM. Add an index, or specify a smaller limit.",
"code" : 96,
"codeName" : "OperationFailed"
}
1 Answer
4 years ago by Anusha
The results returned is occupying more than a maximum of 33554432 bytes of RAM and hence it is throwing the error. You can either increase to give it more memory or modify your query to limit the results based on your requirement.
Consider the below orders
collection as an example:
{ "_id" : 1, "item" : { "category" : "Apple", "type" : "Fruits" }, "quantity" : 10 }
{ "_id" : 2, "item" : { "category" : "Orange", "type" : "Fruits" }, "quantity" : 40 }
{ "_id" : 3, "item" : { "category" : "Carrot", "type" : "Vegetable" }, "quantity" : 15 }
{ "_id" : 4, "item" : { "category" : "lemon", "type" : "Vegetable" }, "quantity" : 30 }
{ "_id" : 5, "item" : { "category" : "Grapes", "type" : "Fruits" }, "quantity" : 5 }
You can write a query to limit the results returned to the size
you want as shown below. This will be beneficial for larger collections.
db.orders.find().sort( { quantity: -1 } ).limit(size)
4 years ago by Jahaan