In MongoDB, sort() method is used to sort the documents in the collection. This method accepts a document containing list of fields along with their sorting order.
The sorting order is specified as 1 or -1.
Syntax:
db.COLLECTION_NAME.find().sort({KEY:1})
Consider an example which has a collection name rookienerd.
This collection has following fields within it.
[ { Course: "Java", details: { Duration: "6 months", Trainer: "Sonoo Jaiswal" }, Batch: [ { size: "Medium", qty: 25 } ], category: "Programming Language" }, { Course: ".Net", details: { Duration: "6 months", Trainer: "Prashant Verma" }, Batch: [ { size: "Small", qty: 5 }, { size: "Medium", qty: 10 }, ], category: "Programming Language" }, { Course: "Web Designing", details: { Duration: "3 months", Trainer: "Rashmi Desai" }, Batch: [ { size: "Small", qty: 5 }, { size: "Large", qty: 10 } ], category: "Programming Language" } ];
Execute the following query to display the documents in descending order.
db.rookienerd.find().sort({"Course":-1})
This will show the documents in descending order.