How to sort documents in the MongoDB collection? In this article, we’ll go over different examples to sort documents in a MongoDB collection using the sort() method. A collection of documents can be sorted by one or more fields using the sort() function. Further, the sort() method is applied to the results of find() operation pipeline to return the documents in a specific order.
Let’s consider a collection student that contains the unsorted document, we will apply the sort() method to these documents by specifying the fields to sort them.
#Create Student collection
db.student.insertMany([
{
_id:1,
sName: “Harry”,
age: 21,
admissionDate: ISODate(“2022-10-23T06:30:22.005Z”),
course:[
{ “name”: “MongoDB” ,”creditHours”: 7 }
]
},
{
_id:2,
sName: “Mark”,
age: 20,
admissionDate: ISODate(“2023-02-13T05:30:22.002Z”),
course:[
{ “name”: “Java” ,”creditHours”: 6}
]
},
{
_id:3,
sName: “Emily”,
age: 24,
admissionDate: ISODate(“2022-05-19T07:21:21.000Z”),
course:[
{ “name”: “Python” ,”creditHours”: 3 }
]
}
])
1. Sort Documents in Ascending order in MongoDB
You can use the sort() method to sort the documents in MongoDB in ascending/alphabetical order by specifying the single field as the argument.
In the following query, we sort a collection named student by the sName field in ascending order. As we have set the sort order as a value 1 that indicates the ascending order. This query would return all the documents in the student collection sorted by the sName field in ascending/alphabetical order.
# Sorting in ascending order
db.student.find().sort({ sName: 1 })
The sorted documents by single field sName in ascending order is displayed in the output.
2. Sort Documents in Descending order
To sort the documents in MongoDB in descending/reverse order by altering the order value to -1 in the sort() method. For example, we have used the following command which sorts the collection student by the single field age in descending order. We used the same sort() method as before, but pass -1 as the value of the field which indicated the descending order.
# Sorting in descending order
db.student.find().sort({ age: -1 })
The output displayed the documents of collection student sorted in descending order by the field age.
3. Sorting by Multiple Fields
However, to sort the documents by multiple fields in MongoDB, we should pass an array of objects to the sort() method. Each object in the array represents a field to sort by, and the order of the objects in the array determines the order in which the fields are sorted.
For example, the student collection is sorted using the following query: initially, we arrange the sName field in ascending order and then the age field in reverse order.
# Sorting by multiple fields
db.student.find().sort([{ sName: 1 }, { age: -1 }])
In the output, documents in the student collection is arranged first by the field sName in ascending order, then the age field is sorted in reverse order.
4. Sort Documents by Date
To sort the documents by a date field, just used the date field as an argument of the sort() method. For example, we have the following command where we sort the document by the date field admissionDate. The field admissionDate contains dates in the format YYYY-MM-DD. We have sorted this date field in ascending order as the value 1 is assigned to it.
# Sorting date field in ascending order
db.student.find().sort({ admissionDate: 1 })
The output generated all the documents which are sorted by the date field in descending order(greater to smaller).
5. Sort Documents by Embedded Fields
Furthermore, we can sort the documents by a nested field in MongoDB. For this, we have to use dot notation to specify the field in the sort() method.
For example, we used the following query to sort the collection student with a field named course. Also, it contains nested fields course and creditHours. Here, we called the sort() method and passed the creditHours field of the course subdocument with the dot notation, and specified the value of 1 to it.
# Sorting by embedded fields
db.student.find().sort({ “course.creditHours”: 1 })
The documents are sorted by the nested field creditHours in ascending order as yielded in the output.
6. Conclusion
The the sort() method is a powerful tool that allows us to sort documents based on one or multiple fields in ascending or descending order. With this method, we can easily organize and analyze data in the MongoDB collections.
More details about this topic can be found here.
How to sort documents in the MongoDB collection? In this article, we’ll go over different examples to sort documents in a MongoDB collection using the sort() method. A collection of documents can be sorted by one or more fields using the sort() function. Further, the sort() method is applied to the results of find() operation Read More MongoDB