Open In App

MongoDB – sort() Method

The sort() method specifies the order in which the query returns the matching documents from the given collection. You must apply this method to the cursor before retrieving any documents from the database. It takes a document as a parameter that contains a field: value pair that defines the sort order of the result set. The value is 1 or -1 specifying an ascending or descending sort respectively.

Syntax:



db.Collection_Name.sort({field_name:1 or -1})

Parameter:

The parameter contains a field: value pair that defines the sort order of the result set. The value is 1 or -1 that specifies an ascending or descending sort respectively. The type of parameter is a document.



Return: 

It returns the documents in sorted order.

Examples:

In the following examples, we are working with:

Database: gfg

Collections: student

Document: Four documents contains name and age of the students.

db.student.find().sort({age:1})

db.student.find().sort({age:-1})

db.student.find().sort({name:1})

db.student.find().sort({name:-1})

Article Tags :