Sorting in MongoDB

Welcome to a tutorial on Sorting in MongoDB.

Sorting data in any database is an important operation in any database management system. The sort() function, in MongoDB, is used to sort the data in a collection. In MongoDB, the sort function accepts a list of values and an integer value 1 or -1 which states whether the collection is to be sorted in ascending (1) or descending (-1) order.

The syntax for the sort function:

 db.collection_name.find().sort({KEY : 1}) 

 

About Sorting

Let’s consider a collection named student containing 3 records. We will try to see how the data can be sorted by making use of the sort() function in MongoDB.

Now, to list down all the data in a collection, the find() command is used. 

Now, to create the same sample data as used here in the example, create a collection named student and insert 3 documents with one field name and some value for it. So, in the next step, we will run the sort command on this sample data.

 

 

Also, let’s run the query below to sort the data by the name field in ascending order:

 db.student.find().sort({name : 1})

 

Next, run the query below to sort the data by the name field in descending order:

 db.student.find().sort({name : -1})

 

Note that if you do not specify the sorting preference (i.e 1 or -1), then by default documents in a collection are sorted in ascending order.