How to Sorting a Collection by Date in MongoDB

Tahseen Tauseef Feb 02, 2024
  1. Use the sort() Function in MongoDB
  2. Sort by Date (Ascending or Descending) in MongoDB
  3. Sort by a Date String in MongoDB
  4. Sort by Date Using Array in MongoDB
How to Sorting a Collection by Date in MongoDB

In this MongoDB tutorial, the problem of sorting a collection in MongoDB is discussed. Different methods to sort the collection in the database are explained briefly.

Use the sort() Function in MongoDB

The problem is solved using the sort() function and the $sort aggregate in MongoDB. You may sort the data in ascending or descending order with this tool.

Example:

db.posts.find().pretty()
{
    "_id" : 1,
    "title" : "MongoDB",
    "body" : "MongoDB is an open-source database",
    "date" : "2021-01-01T00:00:00.000Z",
        "Country" : "United Kingdom"
}
{
    "_id" : 2,
    "title" : "MySQL",
    "body" : "MySQL is a popular open-source relational database management system",
    "date" : ISODate("2020-01-01T00:00:00Z"),
        "Country" : "United States of America"
}
{
    "_id" : 3,
    "title" : "SQL",
    "body" : "SQL is a database computer language",
    "date" : ISODate("2021-01-01T00:00:00Z"),
        "Country" : "New Zealand"
}

Some data are added to the posts collection, and the date field is used to arrange them in ascending order, with earlier dates appearing first.

db.posts.find().sort({ date: 1 }).pretty()
{
    "_id" : 1,
    "title" : "MongoDB",
    "body" : "MongoDB is an open-source database",
    "date" : "2021-01-01T00:00:00.000Z",
        "Country" : "United Kingdom"
}
{
    "_id" : 2,
    "title" : "MySQL",
    "body" : "MySQL is a popular open-source relational database management system",
    "date" : ISODate("2020-01-01T00:00:00Z"),
        "Country" : "United States of America"
}
{
    "_id" : 3,
    "title" : "SQL",
    "body" : "SQL is a database computer language",
    "date" : ISODate("2021-01-01T00:00:00Z"),
        "Country" : "New Zealand"
}

After sorting it, the first document has a date string rather than a date object. The date string appears first, even if the date in document 2 is later.

Sort by Date (Ascending or Descending) in MongoDB

To sort dates in descending order in MongoDB, use the sort() function and give parameters such as date field name and direction (ascending or descending order).

Syntax:

sort(date : 1) #For ascending order
sort(date : -1) #For descending order

Example:

 db.product.find().pretty()
{
        "_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")
}

These are the documents that have been inserted into the product database. Now, it will be sorted in descending order.

Query:

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

Sort by a Date String in MongoDB

There are two alternative techniques in MongoDB for storing date/time. The date object is used in the first method to store the date in the documents.

Syntax:

new Date();

Query:

db.product.insertOne({ "productId" : 101, "productDeliveryDateTime": new Date() });
{
        "acknowledged" : true,
        "insertedId" : ObjectId("611c9e39e1fdc428cf238757")
}

The product is the collection name, and the Date() object was used to insert a date field.

To store the date column in the database, you must use ISODate() in the second method. The International Organization for Standardization (ISO) is a non-profit organization dedicated to developing international standards.

Syntax:

new ISODate();

Query:

db.product.insertOne({ "productId" : 102, "productDeliveryDateTime": new ISODate() });
{
        "acknowledged" : true,
        "insertedId" : ObjectId("611c9e39e1fdc428cf238758")
}

Here, the date field is inserted into the product collection using ISODate(). You can display all the documents using the find() method:

db.product.find().pretty()
{
        "_id" : ObjectId("611c9e39e1fdc428cf238757"),
        "productId" : 101,
        "productDeliveryDateTime" : ISODate("2021-08-18T05:44:25.081Z")
}
{
        "_id" : ObjectId("611ca108e1fdc428cf238758"),
        "productId" : 102,
        "productDeliveryDateTime" : ISODate("2021-08-18T05:56:24.144Z")
}

The most accessible approach to save the date/time is to use the Date object.

If a document has both the Date() string method and the ISODate() method, MongoDB will sort it in the direction of the Date() string method (ascending or descending order). It’s worth noting that after sorting, the first document shown is a date string rather than a Date object.

This appears first even though its date is later than the date in document 2.

Query:

 db.language.find().pretty()
{
        "_id" : 1,
        "item" : {
                "name" : "Python",
                "type" : "Very high level dynamic data types"
        },
        "price" : 2.8,
        "date" : "2021-01-10T00:00:00.000Z"
}
{
        "_id" : 2,
        "item" : {
                "name" : "C++",
                "type" : "High-level computer programming language"
        },
        "price" : 3.9,
        "date" : ISODate("2020-12-01T00:00:00Z")
}
{
        "_id" : 3,
        "item" : {
                "name" : "Java",
                "type" : "Java is a high-level, class-based, object-oriented programming language"
        },
        "price" : 3.2,
        "date" : ISODate("2021-08-01T00:00:00Z")
}

These are some of the documents added to the language collection. You may also use the sort() function to sort them.

Query:

 db.language.find().sort(date:1).pretty()
{
        "_id" : 1,
        "item" : {
                "name" : "Python",
                "type" : "Very high level dynamic data types"
        },
        "price" : 2.8,
        "date" : "2021-01-10T00:00:00.000Z"
}
{
        "_id" : 3,
        "item" : {
                "name" : "Java",
                "type" : "Java is a high-level, class-based, object-oriented programming language"
        },
        "price" : 3.2,
        "date" : ISODate("2021-08-01T00:00:00Z")
}
{
        "_id" : 2,
        "item" : {
                "name" : "C++",
                "type" : "High-level computer programming language"
        },
        "price" : 3.9,
        "date" : ISODate("2020-12-01T00:00:00Z")
}

After sorting all the data in increasing order, you can observe using the date field. The first field is the date string field. The most straightforward approach to saving the date/time is to use the Date object.

There might be several reasons why MongoDB does not function, but you must remember a few procedures to operate with sort by date in MongoDB.

  1. Always remember that you are storing the data in a collection.
  2. There are two ways to store the date field inside the document.
  3. Date() string and ISODate() data type are use to store date in documents.
  4. When you sort the date field using the sort() method, check which data type you used.

Query:

db.document.insertOne({ "productId" : 1001, "productDeliveryDateTime": new Date() });
{
        "acknowledged" : true,
        "insertedId" : ObjectId("611c9e39e1fdc428cf238802")
}

The date is added using the Date() string in this example, and the collection name is the document. You may insert a date in the document using ISODate() in the same way.

Sort by Date Using Array in MongoDB

Use the sort() function to sort by date using an array in MongoDB. You must provide the date field and the direction of sorting in the function (ascending or descending order).

In the following example, add some data in an array format into the collection.

 db.student.insertMany([
      {
        "name"      : "Tom",
        "age"       : 21,
        "timestamp" : new ISODate("2021-04-01" )
      },
      {
        "name"      : "Emma",
        "age"       : 25,
        "timestamp" : new ISODate("2021-10-31" )
      },
      {
        "name"      : "John",
        "age"       : 29,
        "timestamp" : new ISODate("2021-05-02")
      }
]) 
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("611df0e76cc7e05e5e7fe74b"),
                ObjectId("611df0e76cc7e05e5e7fe74c"),
                ObjectId("611df0e76cc7e05e5e7fe74d")
        ]
}

The student is the collection name, and the ISODate() method is used to enter the date. The Date() string method is also available.

Query:

 db.student.find().sort({timestamp:1}).pretty()

{
        "_id" : ObjectId("611df0e76cc7e05e5e7fe74b"),
        "name" : "Tom",
        "age" : 21,
        "timestamp" : ISODate("2021-04-01T00:00:00Z")
}
{
        "_id" : ObjectId("611df0e76cc7e05e5e7fe74d"),
        "name" : "John",
        "age" : 29,
        "timestamp" : ISODate("2021-05-02T00:00:00Z")
}
{
        "_id" : ObjectId("611df0e76cc7e05e5e7fe74c"),
        "name" : "Emma",
        "age" : 25,
        "timestamp" : ISODate("2021-10-31T00:00:00Z")
}

All documents are sorted in ascending order, and the pretty() function is also employed. This allows you to provide the result in a readable fashion.

This article explains sorting collections in MongoDB using different methods in ascending and descending order in detail.

Related Article - MongoDB Sort