May 17, 2021 MongoDB
In MongoDB, the data is sorted using the sort() method, which specifies the sorted fields by parameters and uses 1 and -1 to specify the sort, where 1 is in ascending order and -1 is used for descending ordering.
The basic syntax of the sort() method is as follows:
>db.COLLECTION_NAME.find().sort({KEY:1})
The data in the col collection is as follows:
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"} { "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"} { "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
The following example shows the data in the col collection in descending order of the field title:
>db.mycol.find({},{"title":1,_id:0}).sort({"title":-1}) {"title":"Tutorials Point Overview"} {"title":"NoSQL Overview"} {"title":"MongoDB Overview"} >
Note: If you do not specify how the sort() method is sorted, the default is in ascending order of the document.