MongoDB order by date

In this comprehensive article, I’ll share the proven techniques and optimization strategies I’ve developed through real-world implementations across various industries, helping you understand date-based sorting in MongoDB that can impact performance and user experience.

MongoDB order by date

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

Before diving into the specific methods, let me explain the fundamental concepts of how MongoDB handles date sorting.

MongoDB provides robust support for date and time data through several data types, each optimized for different use cases I’ve encountered across enterprise environments.

Primary Date Types in MongoDB:

  • Date: Standard JavaScript Date object, stored as 64-bit integer (milliseconds since Unix epoch)
  • ISODate: ISO 8601 formatted date strings with timezone support
  • Timestamp: MongoDB internal timestamp type for replication and sharding
  • ObjectId: Contains embedded timestamp information from document creation

Date Storage Characteristics:

  • UTC Storage: All dates stored internally in UTC regardless of input timezone
  • Millisecond Precision: Supports precise timestamps down to the millisecond level
  • Index Compatibility: Date fields can be efficiently indexed for performance
  • Query Flexibility: Supports range queries, comparisons, and aggregation operations

Method 1: Using the sort() method

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

Example 1: Order by id date

When we want to order by the date ID field, we will use the sort() method. Let us learn order by id date in MongoDB with the help of an 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. After executing the above query, I got the expected output as shown in the screenshot below.

MongoDB order by date

Also, check: MongoDB sort by date

Example 2: Order by date in an array

When we have data in an array form in the collection and we want to order by date, then we do so 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 an order by date in an array.

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

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

mongodb order by date desc query

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

Read: MongoDB find multiple values

Example 3: Order by date greater than

We also have to order by either ascending or descending order, for which we will use the sort() method. Let us understand with the help of an example.

Example:

The resulting documents were inserted into the product 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 following query to find documents ordered 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

Read: MongoDB find string contains

Example 4: Order by date less than

Let us find documents that are less than a particular date, and we also have to order by either 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 desc

Now, we will apply the following query to find documents ordered 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

Read: MongoDB text search partial words

Example 5: Order by date between

When we want to find documents between two dates, we use the $gt and $lt operators. We will use the sort() method to order the data in either ascending or descending order. Let us learn to find the document order 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 documents between the specified dates, and the sort() method will help us retrieve the documents in ascending order according to the joining_date field.

How to sort a collection by date in MongoDB?

Read: MongoDB Auto Increment ID

Example 6: Order by date in ascending order.

Let us 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, please refer to the above topic.

mongodb sort by date descending

Now, we will apply the query below 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 desc date

Read: Create an index in MongoDB

Example 7: Order by date without timezone

MongoDB does not support dates without a timezone format. There are two types of log representation, which are alternative ways to store data without a time zone. The first type is milliseconds, 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 that specifies the number of milliseconds.
  • The milliseconds define the integer value used for the date format in MongoDB.
  • Milliseconds will convert the date into the standard date format.

Example:

The example below converts milliseconds into the date format. We have used 1234567890 milliseconds. The output of these milliseconds is January 15, 1970.

> 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, month, and date in full format, and it will 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 example below.

Example:

The following documents have been added to 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 a 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 documents in descending order (-1) based on the timestamp date field.

MongoDB order by date without timezone

Read: MongoDB two-phase commit

Example 8: 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

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

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

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

MongoDB order by date string field

Read: How to drop a database in MongoDB

Example 9: Order by date limit

We will use the limit() method to limit the number of records or documents 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 query below and retrieve 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, ordered by the date field (releaseDate) in descending order (-1).

MongoDB order by date limit

Read: MongoDB join two collections.

Example 10: Order by creation date

The meaning of this topic “order by creation date” is to order the documents of the collection by 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 did in the above topic. For reference, please refer to the topic above.

MongoDB order by creation date

Now, we will apply the query below to the collection to order by the 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

Read: Export MongoDB to CSV

Example 11: 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) and descending (-1) order, respectively.

MongoDB aggregate order by date

Read: MongoDB group by multiple fields

Example 12: 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 order-by operations and define the parameter date field name and direction to retrieve the documents in either ascending or descending order.

Example:

In this example, we will utilize the existing database and collection from the MongoDB database, and use the sort() method to return documents ordered 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 an order by operation. Additionally, we have defined the date field in the sort method with a direction of -1 for descending order.

MongoDB order by date using python

Output:

MongoDB order by date field using python

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

Method 2: Aggregation Pipeline Sorting

For complex date sorting scenarios involving data transformation, grouping, or advanced filtering, MongoDB’s aggregation pipeline provides powerful sorting capabilities.

The aggregation framework’s $sort stage provides enhanced control over sorting operations:

// Basic aggregation sort
db.sales.aggregate([
    { $match: { region: "USA", year: 2024 } },
    { $sort: { saleDate: -1 } },
    { $limit: 100 }
])

// Multiple field sorting with date priority
db.employees.aggregate([
    { $match: { department: "Engineering" } },
    { $sort: { 
        hireDate: -1,    // Primary sort: most recent hires
        lastName: 1      // Secondary sort: alphabetical
    }}
])

Method 3: Compound Sorting with Multiple Date Fields

Many business applications require sorting by multiple date fields, such as systems that track both creation and modification dates, or applications that manage event start and end times.

Multi-Date Field Sorting

// Sort by multiple date fields
db.projects.find().sort({ 
    dueDate: 1,          // Primary: earliest due date first
    createdDate: -1,     // Secondary: most recently created
    lastModified: -1     // Tertiary: most recently modified
})

// Event management sorting
db.events.find({
    location: { $regex: /USA|United States/i }
}).sort({
    startDate: 1,        // Primary: chronological event order
    registrationDeadline: 1,  // Secondary: registration priority
    createdDate: -1      // Tertiary: newest events first
})

Conditional Date Sorting

For applications requiring dynamic sorting based on business logic:

// Sort by different date fields based on conditions
db.tasks.aggregate([
    { $addFields: {
        priorityDate: {
            $cond: {
                if: { $eq: ["$status", "overdue"] },
                then: "$overdueDate",
                else: { $cond: {
                    if: { $eq: ["$status", "pending"] },
                    then: "$dueDate",
                    else: "$completedDate"
                }}
            }
        }
    }},
    { $sort: { priorityDate: 1 } }
])

Method 4: Date Range Sorting and Filtering

Combining date filtering with sorting is crucial for applications serving businesses that require analyzing data within specific time periods.

Time-Based Filtering with Sort

// Recent orders within date range
db.orders.find({
    orderDate: {
        $gte: ISODate("2024-01-01T00:00:00Z"),
        $lte: ISODate("2024-12-31T23:59:59Z")
    },
    shippingAddress: { $regex: /USA|United States/i }
}).sort({ orderDate: -1 })

// Business hours filtering (US Eastern Time consideration)
db.customerCalls.find({
    callDate: {
        $gte: ISODate("2024-11-01T14:00:00Z"), // 9 AM EST
        $lte: ISODate("2024-11-01T22:00:00Z")  // 5 PM EST
    }
}).sort({ callDate: 1 })

Relative Date Sorting

For dynamic applications requiring relative date calculations:

// Documents from last 30 days, sorted by recency
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

db.articles.find({
    publishDate: { $gte: thirtyDaysAgo },
    category: "US-News"
}).sort({ publishDate: -1 })

// This week's data with sorting
const startOfWeek = new Date();
startOfWeek.setDate(startOfWeek.getDate() - startOfWeek.getDay());
startOfWeek.setHours(0, 0, 0, 0);

db.weeklyReports.find({
    reportDate: { $gte: startOfWeek }
}).sort({ reportDate: -1 })

Conclusion

The methods and optimization strategies I’ve shared in this comprehensive guide represent battle-tested approaches that will help you create scalable, efficient MongoDB applications with superior date handling capabilities.

Method Selection Summary:

MethodBest ForPerformanceComplexityUS Business Use Cases
Basic sort()Simple chronological orderingExcellent with indexesLowCustomer orders, transaction logs
Aggregation PipelineComplex transformationsGoodMediumBusiness intelligence, reporting
Compound SortingMulti-criteria orderingVariableMediumProject management, CRM systems
Date Range FilteringTime-bound analysisExcellentLowFinancial reporting, audit trails
Timezone-AwareMulti-region applicationsGoodHighNational retail, distributed teams

You may also like the following MongoDB tutorials:

Top 200 SQL Server Interview Questions and Answers

Free PDF On Top 200 SQL Server Interview Questions And Answers

Download A 40 pages PDF And Learn Now.