Sorting Records on MongoDB Query

Author: Al-mamun Sarkar Date: 2020-09-11 15:07:52

In this lesson, I will show you how you can sort records in ascending and descending order on MongoDB SELECT queries.

Sorting On Records:

Syntax:

db.collection.find().sort({key:1})
db.collection.find().sort({key:-1})

The value of the key will be 1 for ascending order and -1 for descending order.

 

Example:

Sort in Ascending Order:

db.employees.find().sort({salary: 1})

Sort In Descending Order:

db.employees.find().sort({salary: -1})