Progress

MongoDB Sort By Date and Timestamp

MongoDB Sort By Date and Timestamp

Recently I was working on a custom CMS with MongoDB as a database. Building the blog page I realized that the posts were in the order from old to new. Opposite to what we need (display latest posts first).

The solution to this problem was very simple. All I need was to sort the extracted posts data based on their published date in descending order.  MongoDB has built-in methods for sorting.

Descending order of dates means starting from present and going to past. Example: 24 October 2020 > 23 October 2020 > 22 October 2020 ...

MongoDB Sort

MongoDB has a sort() cursor method and $sort aggregation which are very powerful in their specific scenarios.

Sort method and aggregation are used for the same purpose,  to sort the data in ascending or descending order.

In the examples explained in this article, we will look into how to sort data returned from the collections by date and timestamp in MongoDB.

MongoDB Sort by Date or Timestamp

Here is a simple example to sort the collections data in descending order by date in MongoDB.

db.users.find().sort({created_at: -1}).pretty()

The above lines will return the users in descending order of their registration. Example: The user registered today will appear first, registered yesterday at second and so on.

The example works for both Date type and timestamp. However, I want to inform you that MongoDB mentions that timestamps are for internal use and Date object is best to represent dates in MongoDB.

Best Way to Store Date and Time in MongoDB.

MongoDB Aggregation Sort by Date

MongoDB has sort aggregation which is very helpful to sort the data in the desired order. We can use it to sort by date and timestamps in MongoDB.

db.posts.aggregate(
   [
     { $match: { status: "published" } },
     { $sort: { updated_at: -1 } }
   ]
)

Explanation:

  • At the first stage, we match to get only published posts.
  • Then we sort the published posts based on their updated date.
Optimization Rule : It was also possible to sort the data first and then match the 'published' posts. But we know sorting is costly and other posts which are of no use, were also sorted.
Share the Post ;)

Related Posts