The sort() method specifies the order of documents returned from a query. It’s applied to the cursor before fetching results and takes a document of field: value pairs, where 1 means ascending and -1 means descending order. MongoDB generally performs:
- Stable Sort: If the sort operation returns the same results each time it is performed on the same dataset, it is considered a stable sort.
- Unstable Sort: If the results vary each time the sort is performed on the same dataset, it is considered an unstable sort.
Syntax:
db.Collection_Name.sort({field_name:1 or -1})
In the above syntax:
field_name
: The field you want to sort by (e.g., age
, name
, date
).1
for ascending order or -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.
Query:
db.collection.find().sort({ field1: 1, field2: -1 })
Explanation:
- The find() method retrieves documents from the collection.
- The sort() method sorts the results by field1 in ascending order and by field2 in descending order.
- If sort() is not used, MongoDB returns documents in the order they are stored (usually insertion order).
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: Sorting by Age in 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
}
]
Explanation:
- This query sorts the documents by the age field in ascending order.
- As a result, the youngest student ("Bablu", age 18) comes first, followed by others in increasing order of age.
Example 2: Sorting by Age in 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 }
]
Explanation:
- Here, the documents are sorted by age in descending order.
- The oldest student ("Rakesh", age 21) comes first, followed by the others in decreasing order of age.
Example 3: Sorting by Name in Ascending Order.
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
}
]
Explanation:
- The documents are sorted alphabetically by name in ascending order.
- The sorting is case-sensitive, so it follows the lexicographical order, with "Akshay" first, followed by "Bablu", "Gourav", and "Rakesh".
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
}
]
Explanation:
- The documents are now sorted in descending order of name.
- "Rakesh" appears first, followed by "Gourav", "Bablu", and "Akshay".
Sorting operations can be slow on large datasets so it’s important to optimize them for better performance:
- Indexes: Create indexes on the fields that we frequently sort by. MongoDB can use indexes to improve the sorting performance.
allowDiskUse
: When sorting large result sets, enable allowDiskUse
to perform the sort operation on disk rather than in memory.- Limit Results: Use the
limit()
method in combination with sort()
to reduce the number of documents processed.
Explore
MongoDB Tutorial
7 min read
Introduction
Installation
Basics of MongoDB
MongoDB Methods
Comparison Operators
Logical Operators
Arithmetic Operators
Field Update Operators
Array Expression Operators