MongoDB order by date – Detailed Guide

In this MongoDB tutorial, we are going to discuss “MongoDB order by date”. We will cover this topic with different operations and examples. These are the following topics that we are going to cover in this tutorial:

  • MongoDB order by date query
  • MongoDB order by id date
  • MongoDB order by date in an array
  • MongoDB order by date greater than
  • MongoDB order by date less than
  • MongoDB order by date between
  • MongoDB order by date ascending
  • MongoDB order by date without timezone
  • MongoDB order by date string
  • MongoDB order by date limit
  • MongoDB order by creation date
  • MongoDB aggregate order by date
  • MongoDB compass order by date desc
  • MongoDB order by date using python
  • MongoDB order by date vs timestamp

MongoDB order by date query

In MongoDB, the $orderby operator sorts the result of a query in ascending or descending order.

Note that, starting MongoDB version 3.2, the $orderby operator is deprecated in mongosh. In mongosh, we will use the cursor.sort() instead.

Syntax:

db.collection_name.find().sort( { field_name: -1 } )

The sort order can have one of the following values:

ValueDescription
1Sort ascending
-1Sort descending

MongoDB order by id date

When we want to order by date id field for that we will use the sort() method. Let us learn order by id date in MongoDB with the help of an example.

Example:

The subsequent documents were inserted into the “blogs” collection.

db.blogs.insertMany([
{ "timestamp" : ISODate("2020-04-01T00:00:00Z") },
{ "timestamp" : ISODate("2020-10-31T00:00:00Z") },
{ "timestamp" : ISODate("2020-05-02T00:00:00Z") }
])

Now, we will apply the following query to order by id date field:

db.blogs.find().sort( { "_id": -1 })

Here, we have used the sort() method to order by id field in descending order -1.

MongoDB order by id date
MongoDB order by id date

Also, check: MongoDB sort by date

MongoDB order by date in an array

In this section, we will learn how to order by date in an array in MongoDB. When we have data in an array form in the collection and we want to order by as per the date field then we do with the help of the sort() method.

Example:

The following documents were inserted into the store collection.

db.store.insertMany([
{
        "_id" : 1,
        "item" : {
                "name" : "HighLander",
                "type" : "toyota"
        },
        "price" : 2.8,
        "date" : "2021-01-01T00:00:00.000Z"
},
{
        "_id" : 2,
        "item" : {
                "name" : "Swift",
                "type" : "suzuki"
        },
        "price" : 3.9,
        "date" : ISODate("2020-01-01T00:00:00Z")
},
{
        "_id" : 3,
        "item" : {
                "name" : "Mirage G4",
                "type" : "mitsubishi"
        },
        "price" : 3.2,
        "date" : ISODate("2021-01-01T00:00:00Z")
}

])

We will apply the following query to the collection and perform order by date in an array.

 db.store.find().sort({ "date": -1 }).pretty()

Here, we have applied the sort() method and order by descending order -1 as per the date field.

MongoDB order by date in an array
MongoDB order by date in an array

The use of the pretty() method is to return all the documents in easy to read form.

Read: MongoDB find multiple values

MongoDB order by date greater than

In this topic, we will learn to find documents that are greater than a particular date We also have to order by either in ascending or descending order for that we will use the sort() method. Let us understand with the help of an example.

Example:

The resulting documents were inserted into the products collection. The insertMany() method is used to insert multiple documents into the collection.

db.products.insertMany([
    { "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256]},

    { "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},

    { "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},

    { "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024]},

    { "_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : { "ram" : 4, "screen" : 5.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}
 ])

Now, we will apply the below query to find documents order by greater than:

db.products.find({"releaseDate":{ $gt: ISODate("2017-09-01T00:00:00Z") }}).sort({ releaseDate: -1}).pretty()

Here, we have applied the $gt operator to the releaseDate field and found all the documents that are greater than a particular date. After that, we use the sort() method to sort (order by) documents in descending order as per the releaseDate field.

MongoDB order by date greater than
MongoDB order by date greater than

Read: MongoDB find string contains

MongoDB order by date less than

In this topic, we will learn to find documents that are less than a particular date and we also have to order by either in ascending or descending order for that we will use the sort() method.

Example:

In this example, we are using the same products collection as we used in the above topic. For reference, you can check that.

MongoDB order by date less than example
MongoDB order by date less than

Now, we will apply the below query to find documents order by less than:

db.products.find({"releaseDate":{ $lt: ISODate("2014-09-01T00:00:00Z") }}).sort({ releaseDate: 1}).pretty()

Here, we have applied the $lt operator to the releaseDate field and found all the documents that are less than a particular date. After that, we use the sort() method to sort (order by) documents in ascending order as per the releaseDate field.

MongoDB order by date less than
MongoDB order by date less than

Read: MongoDB text search partial words

MongoDB order by date between

When we want to find out the documents between dates then we will use the $gt and $lt operator. And, we will use the sort() method to order by either in ascending or descending order. Let us learn to find the document order by between dates with the help of an example.

Example:

The following documents were inserted into the employee collection.

db.employee.insertMany([
{ "_id": 1, "firstName": "Liam", "joining_date": ISODate("2020-04-02T17:11:01.360Z"), "city": "USA" },
{ "_id": 2, "firstName": "Noah", "joining_date": ISODate("2015-04-02T17:11:01.367Z"), "city": "Canada" },
{ "_id": 3, "firstName": "Patricia", "joining_date": ISODate("2019-03-24T17:00:00.832Z"), "city": "Australia" },
{ "_id": 4, "firstName": "William", "joining_date": ISODate("2016-03-23T18:00:00.832Z"), "city": "New Zealand" }
])

Now, the below query is used to find the documents “order by date between :

db.employee.find({"joining_date":{ $gt: ISODate("2015-04-02T17:11:01.367Z"), $lt: ISODate("2020-04-02T17:11:01.360Z") } }).sort({ joining_date: 1}).pretty()

Here, This query will return all the documents between dates, and the sort() method will help us to retrieve the documents in ascending order as per the joining_date field.

MongoDB order by date between
MongoDB order by date between

Read: MongoDB Auto Increment ID

MongoDB order by date ascending

In this topic, we will learn to find the documents “order by date ascending”. For that, we will use the sort() method and define the date field name with direction 1 for ascending order.

Example:

Here, we will use the employee collection as we used in the above topic. For reference, check the above topic.

MongoDB order by date ascending
MongoDB order by date ascending

Now, we will apply the below query to find documents “order by ascending order”.

db.employee.find().sort({ joining_date: 1})

Here, we have used the sort() method and retrieved all the documents in ascending order.

MongoDB order by date ascending
MongoDB order by date ascending

Read: Create index in MongoDB

MongoDB order by date without timezone

MongoDB does not support the date without the timezone format. There are two types of log representation that is the alternate way to store the date without timezone. The first type is millisecond and the second is (<YYYY-mm-dd HH:MM: ss>).

Date Format in MongoDB without timezone:

1. new Date(<milliseconds>):

  • The millisecond is an integer, and it specifies the number of milliseconds.
  • The milliseconds defines the integer value which was used date formate in MongoDB.
  • Milliseconds will convert the date into standard date format.

Example:

The below example convert milliseconds into the date format. We have used 1234567890 milliseconds output of this milliseconds is 1970-01-15.

> new Date(1234567890)
ISODate("1970-01-15T06:56:07.890Z")

2.  new Date (<YYYY-mm-dd THH:MM: ss>):

  • This format is used to define the year, moth and date in full format and it willl also display the hour, minute and seconds in full format.

Example:

In the example, we will use the date as (“2021-10-20T09:45:45”), and the output of using this date is (“2020-05-15T06:35:45Z”).

new Date("2021-10-20T09:52:45")
ISODate("2021-10-20T04:22:45Z")

Now, we will learn to find the documents “order by date without timezone” with the help of the below example.

Example:

The following documents were inserted into the blog’s collection.

db.blogs.insertMany([
{ "timestamp" : ISODate("2020-04-01T00:00:00Z") },
{ "timestamp" : ISODate("2020-10-31T00:00:00Z") },
{ "timestamp" : ISODate("2020-05-02T00:00:00Z") }
])

Here, we inserted the date field without timezone to return all the documents “order by date” either in ascending or descending order.

db.blogs.find().sort({ timestamp: -1})

This query will return all the documents in descending order (-1) as per the timestamp date field.

MongoDB order by date without timezone
MongoDB order by date without timezone

Read: MongoDB two-phase commit

MongoDB order by date string

In MongoDB, we will use the Date() function to create the date field as a string. We will insert some documents into the database and after that return the documents “order by date string”.

Example:

The following documents were inserted into the sales collections.

db.sales.insertMany([
    {
      "_id" : 1,
      "item" : "abc",
      "price" : 10,
      "quantity" : 22,
      "date" : new Date()
    },
    {
      "_id" : 2,
      "item" : "pqr",
      "price" : 60,
      "quantity" : 2,
      "date" : new Date()
    },
    {
      "_id" : 3,
      "item" : "xyz",
      "price" : 30,
      "quantity" : 12,
      "date" : new Date()
    }
])
MongoDB order by date string
MongoDB order by a date string

Here, we successfully inserted the date as a string. After that, we will apply the below query and find documents “order by date string”.

db.sales.find().sort({ date: 1, price: -1})

Here, we applied the sort() method and return the documents when the date field is in ascending order and the price field is in descending order.

MongoDB order by date string field
MongoDB order by date string field

Read: How to drop a database in MongoDB

MongoDB order by date limit

In this topic, we will learn to return the documents “order by date limit”. And, we will use the limit() method to limit the number of records or documents that we want. Let us understand with the help of an example.

Example:

The subsequent documents were inserted into the products collection:

db.products.insertMany([

    { "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate": ISODate("2011-05-14"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 },"color":["white","black"],"storage":[64,128,256]},

    { "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate": ISODate("2011-09-01") , "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 },"color":["white","black","purple"],"storage":[128,256,512]},

    { "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate": ISODate("2015-01-14"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 },"color":["blue"],"storage":[16,64,128]},

    { "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate": ISODate("2020-05-14"),"spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256,1024]},

    { "_id" : 5, "name" : "SmartPhone", "price" : 599,"releaseDate": ISODate("2022-09-14"), "spec" : { "ram" : 4, "screen" : 5.7, "cpu" : 1.66 },"color":["white","orange","gold","gray"],"storage":[128,256]}

])

After that, we will apply the below query and find documents as “order by date limit”.

db.products.find().limit(3).sort({ releaseDate: -1})

Here, we have applied the limit() method to limit the number of records and by using the sort() method order by date field (releaseDate) in descending order (-1).

MongoDB order by date limit
MongoDB order by date limit

Read: MongoDB join two collections

MongoDB order by creation date

The meaning of this topic “order by creation date” is to order by the documents of the collection as per the date field. For that, we will use the sort() method. We can sort the documents either in ascending or descending order by using 1 or -1 respectively.

Example:

In this example, we will use the products collection as we used the above topic. For reference, you can check the above topic.

MongoDB order by creation date
MongoDB order by creation date

Now, we will apply the below query to the collection to order by date field in ascending order.

db.products.find().sort({ releaseDate: 1})

Here, we have used the sort() method and defined the date field releaseDate to order by in ascending order.

MongoDB order by date as per creation field
MongoDB order by creation date

Read: Export MongoDB to CSV

MongoDB aggregate order by date

The $sort operator is used in the aggregation function to order by any field. Here, we will learn to use the aggregate() function to order by the date field.

Example:

The following documents were inserted into the store collection.

db.store.insertMany([
  { 
    "_id" : 1,
    "name" : "Google Chrome", 
    "lastModified" : Date()
  },
  { 
    "_id" : 2,
    "name" : "UC Browser", 
    "lastModified" : Date()
  },
  { 
    "_id" : 3,
    "name" : "Microsoft Edge", 
    "lastModified" : Date()
  }
])

After that, we will apply the aggregate() function and return documents “order by the date” field using the $sort operator.

db.store.aggregate([ { $sort: { lastModified: 1, name: -1}} ] )

Here, we have applied the $sort operator in the aggregate() function and defined two fields the lastModified and name in ascending (1), descending (-1) order respectively.

MongoDB aggregate order by date
MongoDB aggregate order by date

Also, Check: Import CSV into MongoDB

MongoDB compass order by date desc

In this topic, you will learn to perform an order by operation according to the date field in descending order using the MongoDB Compass.

The order by operations is used to return the documents either in ascending or descending order. Let us understand with the help of an example.

Example:

You have to follow the below steps without any falls to understand the example. In this example, we will perform the order by operation and return the documents in descending order.

  • Open the MongoDB compass and connect to the server.
  • Select the database and collection in which you want to perform the operation.
  • You can also create a new database and insert the documents into the collection.
  • Here, we are using the database and collection is mydatabase, sales respectively.
MongoDB compass order by
Select the database and collection
  • Click on the OPTIONS drop down list button.
  • And, you have to provide the FILTER as per given condition.
MongoDB compass order by date descending
MongoDB compass order by date in descending

Here, we have applied the condition on the SORT filter to return the documents in descending order as per the date field.

  • After that, click on the FIND button.
MongoDB compass order by date desc
MongoDB compass order by date in descending

We have successfully returned all the documents in descending order as per the date field.

Read: MongoDB group by multiple fields

MongoDB order by date using python

In this topic, we will learn to find the documents in order by date field using python. We will use the sort() method for the order by operations and define the parameter date field name and direction to retrieve the documents either in ascending or descending order.

Example:

In this example, we will use the existing database and collection from the MongoDB database and use the sort() method to return documents to order by the date field.

import pymongo

myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017")
mydb = myclient["mydatabase"]
mycol = mydb["sales"]

mydoc = mycol.find().sort( "date", -1 )

for x in mydoc:
  print(x)

Here, we have imported the pymongo library to make the connection between Python and MongoDB. The MongoClient class is used to make connections with the MongoDB server.

After that, select the database and collection and use the sort method to perform order by operation. And, we have defined the date field in the sort method with direction -1 for order by descending order.

MongoDB order by date using python
MongoDB order by date using python

Output:

MongoDB order by date field using python
MongoDB order by date field using python

We have successfully retrieved all the documents “order by date field using python” in descending order.

Read: MongoDB drop collection

MongoDB order by date vs timestamp

In this topic, we will learn about order by date vs timestamp. And, we will also cover an example so you can understand it easily.

What is the difference b/w the date and timestamp?

DATE: We only define the date part but no time part. The date value is in YYYY-MM-DD format.

TIMESTAMP: We define both the date and time part. This will display in this YYYY-MM-DD HH:MM:SS format.

We have already covered the topic order by date field in this article. you can learn from the previous post. Furthermore, we will learn about the order by timestamp field with the help of an example.

Example:

The subsequent documents were inserted into the timestamp collection.

db.timestamp.insertMany([
    {"timestamp" : new ISODate("2021-04-01" )},
    {"timestamp" : new ISODate("2021-10-31" )},
    {"timestamp" : new ISODate("2021-08-02" )},
    {"timestamp" : new ISODate("2021-05-02" )}
])

After that, we will apply the following query to order by timestamp in descending order (-1).

db.timestamp.find().sort({ "timestamp": -1 })
MongoDB order by date vs timestamp
MongoDB order timestamp

We successfully retrieved all the documents of the timestamp collection in descending order.

You may also like below MongoDB tutorials:

So, In this tutorial, we have learned “MongoDB order by date” using different approaches with examples. These are the following topics that we covered in this tutorial:

  • MongoDB order by date query
  • MongoDB order by id date
  • MongoDB order by date in an array
  • MongoDB order by date greater than
  • MongoDB order by date less than
  • MongoDB order by date between
  • MongoDB order by date ascending
  • MongoDB order by date without timezone
  • MongoDB order by date string
  • MongoDB order by date limit
  • MongoDB order by creation date
  • MongoDB aggregate order by date
  • MongoDB compass order by date desc
  • MongoDB order by date using python
  • MongoDB order by date vs timestamp