MongoDB – Sort Records

MongoDB – Sort Records

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

The sort() Method

To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.

Syntax

The basic syntax of sort() method is as follows −

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

Example

Consider the collection myycol has the following data.

{ "_id" : 0, "name" : "aimee Zank", "class" : 10 }
{ "_id" : 1, "name" : "Aurelia Menendez", "class" : 11 }
{ "_id" : 2, "name" : "Salena Olmos", "class" : 12 }
>

Following example will display the documents sorted by id in the descending order.

> db.stuDetails.find({},{"name":1,"_id":0}).sort({"_id":-1})
{ "name" : "Salena Olmos" }
{ "name" : "Aurelia Menendez" }
{ "name" : "aimee Zank" }

Please note, if you don't specify the sorting preference, then sort() method will display the documents in ascending order.

MongoDB – Limit Records (Prev Lesson)
(Next Lesson) MongoDB – Indexing