MongoDB Sorting
MongoDB sort() Method
In MongoDB, the sort() method is used to sort data. The sort() method can specify the fields to sort by and uses 1 and -1 to define the sorting order, where 1 is for ascending order and -1 is for descending order.
Syntax
The basic syntax of the sort() method is as follows:
>db.COLLECTION_NAME.find().sort({KEY:1})
Example
The data in the col collection is as follows:
{ "_id" : ObjectId("56066542ade2f21f36b0313a"), "title" : "PHP Tutorial", "description" : "PHP is a powerful server-side scripting language for creating dynamic and interactive websites.", "by" : "tutorialpro.org", "url" : "http://www.tutorialpro.org", "tags" : [ "php" ], "likes" : 200 }
{ "_id" : ObjectId("56066549ade2f21f36b0313b"), "title" : "Java Tutorial", "description" : "Java is a high-level programming language introduced by Sun Microsystems in May 1995.", "by" : "tutorialpro.org", "url" : "http://www.tutorialpro.org", "tags" : [ "java" ], "likes" : 150 }
{ "_id" : ObjectId("5606654fade2f21f36b0313c"), "title" : "MongoDB Tutorial", "description" : "MongoDB is a NoSQL database.", "by" : "tutorialpro.org", "url" : "http://www.tutorialpro.org", "tags" : [ "mongodb" ], "likes" : 100 }
The following example demonstrates sorting the data in the col collection by the likes field in descending order:
>db.col.find({},{"title":1,_id:0}).sort({"likes":-1})
{ "title" : "PHP Tutorial" }
{ "title" : "Java Tutorial" }
{ "title" : "MongoDB Tutorial" }
>