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 : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"}
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"}
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}

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

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

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



Frequently Asked Questions

+
Ans: MongoDB - Limit Records view more..
+
Ans: MongoDB - Projection view more..
+
Ans: MongoDB - Delete Document view more..
+
Ans: MongoDB - Sort Records view more..
+
Ans: MongoDB - Indexing view more..
+
Ans: MongoDB - Aggregation view more..
+
Ans: MongoDB - Replication view more..
+
Ans: MongoDB - Sharding view more..
+
Ans: MongoDB - Create Backup view more..
+
Ans: MongoDB - Deployment view more..
+
Ans: MongoDB - Java view more..
+
Ans: MongoDB - PHP view more..
+
Ans: MongoDB - Relationships view more..
+
Ans: MongoDB - Database References view more..
+
Ans: MongoDB - Covered Queries view more..
+
Ans: MongoDB - Atomic Operations view more..
+
Ans: MongoDB - Advanced Indexing view more..
+
Ans: MongoDB - Indexing Limitations view more..




Rating - NAN/5
503 views

Advertisements