English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MongoDB Record Sorting

In this chapter, we will learn how to sort records in MongoDB.

sort() method

To sort documents in MongoDB, you need to usesort()method. This method accepts a document containing a list of fields and their sorting order. To specify the sorting order, please use1and-1.1represents ascending order,-1represents descending order.

Syntax

sort()The basic syntax of the method is as follows-

>db.COLLECTION_NAME.find().sort({KEY:}}1}

Example

Assuming the collection myycol has the following data.

{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"}
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"}
{_id : ObjectId("507f191e810c19729de860e3"), title: "w3codebox Overview"}

The following example will display documents sorted in descending order by title.

>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1}
{"title":"w3codebox Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>

Please note that if you do not specify a sort preference, thensort()Methods will display documents in ascending order.