In MongoDB, sort() method is used to get the documents in ascending or descending order corresponding to the document key.
Ascending Order
to get the documents in the ascending order through sort({key_name:1}) method
Syntax:-
db.collectionName.find().sort({key_name:1});
Suppose, you have employees collection
[
{
"_id" : ObjectId("5f26e736deec6e20ea057831"),
"name" : "John",
"age" : 35,
"department" : "department A",
"salary" : 200000
},
{
"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
"name" : "Rom",
"age" : 30,
"department" : "department A",
"salary" : 70000
},
{
"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
"name" : "Andrew",
"age" : 33,
"department" : "department C",
"salary" : 20000
}
]
Now, you want to get the documents in ascending Order corresponding to name wise.
> db.employees.find().sort({name:1}).toArray();
Output:-
[
{
"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
"name" : "Andrew",
"age" : 33,
"department" : "department C",
"salary" : 20000
},
{
"_id" : ObjectId("5f26e736deec6e20ea057831"),
"name" : "John",
"age" : 35,
"department" : "department A",
"salary" : 200000
},
{
"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
"name" : "Rom",
"age" : 30,
"department" : "department A",
"salary" : 70000
}
]
Descending Order
to get the documents in the descending order through sort({key_name:-1}) method
Syntax:-
db.collectionName.find().sort({key_name:-1});
Suppose, you want the get the documents from the employees collection in descending order corresponding to name wise.
> db.employees.find().sort({name:-1}).toArray();
Output:-
[
{
"_id" : ObjectId("5f26e7c0deec6e20ea057832"),
"name" : "Rom",
"age" : 30,
"department" : "department A",
"salary" : 70000
},
{
"_id" : ObjectId("5f26e736deec6e20ea057831"),
"name" : "John",
"age" : 35,
"department" : "department A",
"salary" : 200000
},
{
"_id" : ObjectId("5f26e9dedeec6e20ea057835"),
"name" : "Andrew",
"age" : 33,
"department" : "department C",
"salary" : 20000
}
]