MongoDB sort() function

MongoDB sort() function is used for sorting the result. We can sort any query result using this function. The sort() function takes an object as a parameter. The parameter is in a set of key/value pairs, where the keys are the key names and the values are the sort direction. This direction can be either ascending(1) or descending(-1). We can also sort by one or more keys or provide multiple keys, the result will be sorted in that order.

Syntax sort() function

db.collection.find().sort({field : sort_order})

The 'field' specifies to sort by and the 'sort_order' can be either ascending(1) or descending(-1).





Example sort() function

Suppose we have the following 'students' collection.

{ "_id" : ObjectId("5b7ddc4f529cbc23546dc4c7"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("5b7ddf10529cbc23546dc4c8"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4c9"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4ca"), "name" : "Mary Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4cb"), "name" : "Priska Somya", "age" : 12, "class" : "6A" }
mongodb sort

and, we want to find all students sorted by their name in ascending order.

db.students.find().sort({name : 1});
Output of the above code -
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4c9"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7ddc4f529cbc23546dc4c7"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4ca"), "name" : "Mary Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4cb"), "name" : "Priska Somya", "age" : 12, "class" : "6A" }
{ "_id" : ObjectId("5b7ddf10529cbc23546dc4c8"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
mongodb sort





Read more articles


General Knowledge



Learn Popular Language