Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MongoDB sort


May 17, 2021 MongoDB


Table of contents


MongoDB sort


MongoDB sort() method

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.

Grammar

The basic syntax of the sort() method is as follows:

>db.COLLECTION_NAME.find().sort({KEY:1})

Instance

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.