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.

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.

Behavior of Sort method in MongoDB

  • In MongoDB, the sort() method is used to sort the results of a query in either ascending or descending order based on one or more fields.
  • The sort() method takes an object as an argument, where each field to sort by is a key and the value is either 1 for ascending order or -1 for descending order.

Here’s a basic example of using the sort() method:

db.collection.find().sort({ field1: 1, field2: -1 })

Explanation:

  • In this example, the find() method retrieves documents from the collection, and the sort() method sorts the results first by field1 in ascending order, and then by field2 in descending order.
  • If the sort() method is not provided, MongoDB will return the documents in the order they are stored in the database, which is typically the order in which they were inserted.
  • It’s important to note that the sort() method can impact performance, especially when sorting large result sets. In such cases, it’s recommended to use indexes to improve the performance of sorting operations.

Examples of MongoDB sort()

To understand sort method in MongoDB we need a collection called students on which we will perform various operations and queries. 

[
{
_id: ObjectId('600f1abb923681e7681ebdce'),
name: 'Akshay',
age: 19
},
{ _id: ObjectId('600f1abb923681e7681ebdcf'), name: 'Bablu', age: 18 },
{
_id: ObjectId('600f1abb923681e7681ebdd0'),
name: 'Rakesh',
age: 21
},
{
_id: ObjectId('600f1abb923681e7681ebdd1'),
name: 'Gourav',
age: 20
}
]

Example 1: Ascending Order

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

Output:

[
{ _id: ObjectId('600f1abb923681e7681ebdcf'), name: 'Bablu', age: 18 },
{
_id: ObjectId('600f1abb923681e7681ebdce'),
name: 'Akshay',
age: 19
},
{
_id: ObjectId('600f1abb923681e7681ebdd1'),
name: 'Gourav',
age: 20
},
{
_id: ObjectId('600f1abb923681e7681ebdd0'),
name: 'Rakesh',
age: 21
}
]

Example 2: Descending Order

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

Output:

[
{
_id: ObjectId('600f1abb923681e7681ebdd0'),
name: 'Rakesh',
age: 21
},
{
_id: ObjectId('600f1abb923681e7681ebdd1'),
name: 'Gourav',
age: 20
},
{
_id: ObjectId('600f1abb923681e7681ebdce'),
name: 'Akshay',
age: 19
},
{ _id: ObjectId('600f1abb923681e7681ebdcf'), name: 'Bablu', age: 18 }
]

Example 3: Ascending order of student name:

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

Output:

[
{
_id: ObjectId('600f1abb923681e7681ebdce'),
name: 'Akshay',
age: 19
},
{ _id: ObjectId('600f1abb923681e7681ebdcf'), name: 'Bablu', age: 18 },
{
_id: ObjectId('600f1abb923681e7681ebdd1'),
name: 'Gourav',
age: 20
},
{
_id: ObjectId('600f1abb923681e7681ebdd0'),
name: 'Rakesh',
age: 21
}
]

Example 4: Descending order of student name::

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

Output:

[
{
_id: ObjectId('600f1abb923681e7681ebdd0'),
name: 'Rakesh',
age: 21
},
{
_id: ObjectId('600f1abb923681e7681ebdd1'),
name: 'Gourav',
age: 20
},
{ _id: ObjectId('600f1abb923681e7681ebdcf'), name: 'Bablu', age: 18 },
{
_id: ObjectId('600f1abb923681e7681ebdce'),
name: 'Akshay',
age: 19
}
]

Conclusion

Overall, the sort() method in MongoDB is a powerful tool for arranging query results in either ascending or descending order based on specified fields. Understanding its behavior and optimizing its usage can significantly improve the performance of database queries, especially when dealing with large datasets. By using the sort() method effectively, developers can ensure efficient data retrieval and manipulation in MongoDB.



Contact Us