MongoDB sort()
- The sort() method in MongoDB is used to specify the order in which the query returns matching documents from a given collection. It must be applied 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.
- If a sort returns the same result every time we perform on the same data, then such type of sort is known as a stable sort.
- If a sort returns a different result every time we perform on the same data, then such type of sort is known as unstable sort.
- MongoDB generally performs a stable sort unless sorting on a field that holds duplicate values.
- We can use the limit() method with the sort() method, it will return the first m documents, where m is the given limit.
- MongoDB can find the result of the sort operation using indexes.
- If MongoDB does not find sort order using index scanning, then it uses the top-k sort algorithm.
Syntax:
db.Collection_Name.sort({field_name:1 or -1})
Explanation: This query sorts the documents in Collection_Name
by field_name
in ascending order and -1 for descending order.
MongoDB – sort() Method
In MongoDB, the sort()
method is used to specify the order in which the query returns matching documents from a collection. It allows users to arrange documents in either ascending (1) or descending (-1) order based on the values of one or more fields. In this article, We will learn about the MongoDB sort() method in detail by understanding the various examples and so on.
Contact Us