Sorting is one of the necessary database operations. It helps to simplify readability and sort the data as per the requirement. In this chapter, you will learn about sorting concept and how it can be implemented in the MongoDB database.

What Is Sorting in Database?

Sorting can be defined as the ordering of data in the increase as well as decreasing manner based on a number of linear relationships among the various data items residing in the database. Sorting can be performed on entities like information (which includes names and facts), numbers as well as records. Sorting also increases the readability and uniformity to the displayed data from the database.

sort() Method of MongoDB

For sorting your MongoDB documents, you need to make use of the sort() method. This method will accept a document that has a list of fields and the order for sorting. For indicating the sorting order, you have to set the value 1 or -1 with the specific entity based on which the ordering will be set and displayed. One indicates organizing data in ascending order while -1 indicates organizing in descending order.


The basic syntax for the sort() method is:

db.collection_name.find().sort({FieldName1: sort order 1 or -1, FieldName2: sort order})


Consider a collection that is having the following data:

{ "_id" : ObjectId(5983548781331abf45ec5), "topic":"Cyber Security"}
{ "_id" : ObjectId(5565548781331aef45ec6), " topic ":"Digital Privacy"}
{ "_id" : ObjectId(5983549391331abf45ec7), " topic ":"Application Security Engineering"}

Suppose I want to get data only from the topic field from all the documents in ascending order, then it will be executed like this:


db.techSubjects.find({}, {"topic":1, _id:0}).sort({"topic":1})

MongoDB projection is used to display only selected fields of ​​the document.
The above statement will result in:


It is to be noted that in case you do not state or explicitly define the sorting preference (1 or -1), then, the sort() method will exhibit your documents in ascending order by default.

To display the topic field of all the techSubjects in descending order:


Keep in mind that you can also sort the documents based on the field you do not want to display.

Metadata Sort Technique

You can also specify the sorting of parameters through a new field name for the calculated metadata which you can specify under the $meta expression as a value. Here is a sample document that specifies a descending sort using the metadata "textCount":


{ count: { $meta: "textCount" } }

Here this specified metadata will determine the sort order.

Here is the syntax:


<MongoDB query statement>,
{ value: { $meta: <metadataKeyword> } }


{ count: { $meta: "textCount" } }
).sort( { count: { $meta: "textCount" } } )

Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram