Sort Records in MongoDB


The sort() Method

We need to use sort() method to sort documents in MongoDB, it accepts a document field 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:

Basic syntax of the sort() method is given below


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


Example: Point out the collection testCol has the following data


{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview", "by":"codefari.com"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":" ASP.Net Over view ", "by":"codefari.com"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":" SQL Server 2014", "by":"codefari.com"}


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


>db.testCol.find({},{"title":1,_id:0}).sort({"title":-1})
{"title":" SQL Server 2014"}
{"title":" MongoDB Overview "}
{"title":" SQL Server 2014"}
> 



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

No comments:

Post a Comment

Please do not enter any spam link in the comment box.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...