MongoDB sort() method

The sort() method is a command in mongoDB that helps sort documents. We can sort documents in ascending or descending order based on a particular field.

sort() method Syntax :

The syntax of the sort() method is −
Note:-  1 is for ascending order and -1 is for descending order. The default value is 1.

 
\\sort() method in MongoDB 
db.collection_name.find().sort({field_key:1 or -1})


sort() method Example :

collection employee contains following documents: −

\\Example of sorting a document in MongoDB
> db.employee.find().pretty()
{
"_id" : ObjectId("59bf63380be1d7770c3982af"),
"employee_name" : "Rajesh",
"employee_id" : 2002,
"employee_age" : 24
}
{
"_id" : ObjectId("59bf63500be1d7770c3982b0"),
"employee_name" : "Jugal",
"employee_id" : 2003,
"employee_age" : 25
}
{
"_id" : ObjectId("59bf63650be1d7770c3982b1"),
"employee_name" : "Yash",
"employee_id" : 2004,
"employee_age" : 23
}


\\documents in descending order:
> db.employeedata.find({}, {"employee_id": 1, _id:0}).sort({"employee_id": -1})
{ "employee_id" : 2004 }
{ "employee_id" : 2003 }
{ "employee_id" : 2002 }
------------------------
------------------------
\\documents in ascending order:
> db.employeedata.find({}, {"employee_id": 1, _id:0}).sort({"employee_id": 1})
{ "employee_id" : 2002 }
{ "employee_id" : 2003 }
{ "employee_id" : 2004 }



Visit :


Discussion



* You must be logged in to add comment.