In MongoDB, sort() method is used to get the documents in ascending or descending order corresponding to the document key.
Syntax:-
db.collectionName.find().sort({key:1});
Note:- 1 is used to get the documents in ascending order.
Consider, 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("5f26e9dedeec6e20ea057833"), "name" : "Tony", "age" : 31, "department" : "department B", "salary" : 40000 }, { "_id" : ObjectId("5f26e9dedeec6e20ea057834"), "name" : "Peter", "age" : 32, "department" : "department B", "salary" : 30000 }, { "_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("5f26e9dedeec6e20ea057834"), "name" : "Peter", "age" : 32, "department" : "department B", "salary" : 30000 }, { "_id" : ObjectId("5f26e7c0deec6e20ea057832"), "name" : "Rom", "age" : 30, "department" : "department A", "salary" : 70000 }, { "_id" : ObjectId("5f26e9dedeec6e20ea057833"), "name" : "Tony", "age" : 31, "department" : "department B", "salary" : 40000 } ]
Descending order:-
Syntax:-
db.collectionName.find().sort({key:-1});
Note:- -1 is used to get the documents in descending order.
Now, you want the get the documents in descending order corresponding to name wise.
> db.employees.find().sort({name:-1}).toArray();
Output:-
[ { "_id" : ObjectId("5f26e9dedeec6e20ea057833"), "name" : "Tony", "age" : 31, "department" : "department B", "salary" : 40000 }, { "_id" : ObjectId("5f26e7c0deec6e20ea057832"), "name" : "Rom", "age" : 30, "department" : "department A", "salary" : 70000 }, { "_id" : ObjectId("5f26e9dedeec6e20ea057834"), "name" : "Peter", "age" : 32, "department" : "department B", "salary" : 30000 }, { "_id" : ObjectId("5f26e736deec6e20ea057831"), "name" : "John", "age" : 35, "department" : "department A", "salary" : 200000 }, { "_id" : ObjectId("5f26e9dedeec6e20ea057835"), "name" : "Andrew", "age" : 33, "department" : "department C", "salary" : 20000 } ]