Monday 29 May 2017

MONGODB Sorting Records ~ GNIITHELP



Sorting in MongoDB

Sorting the data in any database is one of the vital operations in any database management system. MongoDB provides sort() function in order to sort the data in a collection. Sort function in MongoDB accepts a list of values and an integer value 1 or -1 which states whether the collection to be sorted in ascending (1) or descending (-1) order.
Syntax for sort function:
db.collection_name.find().sort({KEY : 1}) 
Consider a collection named student containing 3 records. Let us now see how the data can be sorted using the sort() function in MongoDB.
To list down all the data in a collection, use the find() command. To create the same sample data as used here in the example, create a collection named student and insert 3 documents with one field name and some value for it. In the next step we will run the sort command on this sample data.
List down collection data in MongoDB
Now run the below query to sort the data by the name field in ascending order :
db.student.find().sort({name : 1})
List down collection data in MongoDB
Now run the below query to sort the data by the name field in descending order :
db.student.find().sort({name : -1})
List down collection data in MongoDB
NOTE : If you do not specify the sorting preference(i.e 1 or -1), then by default documents in a collection are sorted in ascending order.

No comments:

Post a Comment