Home >>MongoDB Tutorial >MongoDB Sort Records

MongoDB Sort Records

How to Sort Records in MongoDB

The sort() Method

You need to use the sort() method in trying to process documents in MongoDB. A document containing a list of fields along with their sorting order is approved by the method. 1 and -1 are used to define the sorting order. 1 is used for the ascending order, while the descending order uses -1.

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 : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"}
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"}
{_id : ObjectId("507f191e810c19729de860e3"), title: "phptpoint  Overview"}
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":"Phptpoint Overview"}
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}
>

If you do not specify a sorting preference, please note that the sort() method shows the documents in ascending order.


No Sidebar ads