MongoDB - Sort Records

MongoDB - Sort Records 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. specify sorting order 1 and -1 are used.1 is used for ascending order while -1 is used for descending order.


The basic syntax of sort() method is as follows >db.COLLECTION_NAME.find().sort({KEY:1})


Consider the collection myycol has the following data.

         { "_id" : ObjectId(VV^euD3afPL^5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(VV^euD3afPL^6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(VV^euD3afPL^7), "title":" Welookups"}

Following example will display the documents sorted by title in the descending order.
{"title":"NoSQL Overview"}
{"title":"MongoDB Overview"}

Welookups is optimized for learning.Copy right 2018 kumar aditya singh .
All Right Reserved and you agree to have read and accepted our term and condition.
All Rights Reserved.