MongoDB Sort

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 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.


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).


Suppose we have the following students data.

mongodb sort

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

db.students.find().sort({name : 1});
mongodb sort

Read more articles

General Knowledge

Learn Popular Language