As, sorting can be performed either in ascending or descending manner; similarly, the sort by date also allows retrieving documents in both orders. After getting through this post, you’ll be able to apply the sort by date functionality in MongoBD.
How do you sort documents by date in MongoDB
In this section, we will explain the possible ways to sort the documents by date in MongoDB. The sort by date is a functionality of the “$sort” operator and “sort()” method of MongoDB. Therefore, it is observed that one can retrieve documents with respect to the date field by following ways:
Using sort() method : The syntax to use sort() method is given below:
Using $sort operator : The $sort operator is used inside aggregation() method and you can use the following syntax to apply $sort operator:
In the above syntaxes, the instances used are:
- collection-name: Refers to the name of the collection where you want to apply this method.
- <date-field>: It must be replaced by the name of the field that contains the date function.
- <order>: Represents the order; and the <order> will be swapped by “1” for ascending or “-1” for descending order.
The upcoming section contains several examples that explains the concept of sort() method and $sort operator to sort documents by date.
Retrieving documents in sort by date order
Firstly, let’s have a look at the documents present in our “staff” collection. The output shows that each document has a date field named “JoiningDate“:
Example: Using the sort() method
Following the syntax of “sort()” method, the command written below will sort the documents in ascending order. Moreover, the sorting is performed on the “JoiningDate” field that represents the date of joining of staff members.
Or you get the output in descending order by issuing the command written below:
Example: Using $sort operator
Referring to the documents of the “staff” collection used in the above example. The below-mentioned commands will sort the documents with respect to the “JoiningDate” field using the $sort operator in the aggregate method.
For Ascending order, use the command written below:
For Descending order, use the command provided below:
Note: If you insert other than (-1 or 1) for ordering; you may face the error shown in the output below:
MongoDB provides an extensive list of operators and methods to store and retrieve documents from a collection. The sorting in MongoDB can be performed from multiple perspectives; like sort by date can be used to print the documents in ascending/descending order with respect to the date field. In this post of MongoDB tutorials, we have listed down several possible ways to sort the documents with respect to date. This guide consists of a few examples that show the usage of the $sort operator with aggregate method and sort() method. Both ways are used to retrieve the documents by date function.