JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Sort a collection by date in MongoDB

Author:JIYIK Last Updated:2025/04/11 Views:

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


Using sort() function in MongoDB

This problem is solved using the MongoDB sort()function and the $sort aggregation. You can use this tool to sort the data in ascending or descending order.

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 is added to the posts collection, and the date field is used to sort them in ascending order, with older dates 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, the first document has a date string instead of a date object. The date string comes first, even though the date in document 2 is later.


Sorting by date (ascending or descending) in MongoDB

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

grammar:

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"
}

Sorting by date string in MongoDB

There are two alternative techniques for storing date/time in MongoDB. In the first method, a Date object is used to store the date in the document.

syntax:

new Date();

Query:

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

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

To store a 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.

grammar:

new ISODate();

Query:

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

Here, the date field is inserted into the products collection using ISODate(). You can display all 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 convenient way to store date/time is to use the Date object.

If a document has both Date()a string method and an ISODate() method, MongoDB will sort it in the direction of the Date() string method (ascending or descending). Note that after sorting, the first document displayed is the date string rather than the Date object.

It 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 can also sort them using the sort() function.

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 all the data is in ascending order, you can observe using the date fields. The first field is the date string field. The most direct way to save date/time is to use the Date object.

There could be many reasons why MongoDB is not working, but you must remember some procedures for sorting operations by date in MongoDB.

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

Query:

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

In this example, the date is added using Date() string and the collection name is Documents. You can insert the date in the document in the same way using ISODate().


Sorting by date using arrays in MongoDB

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

In the following example, some data in array format is added to 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")
        ]
}

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

ask:

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 using pretty()the function. This allows you to serve the results in a readable manner.

This article explains in detail the different methods used to sort a collection in ascending and descending order in MongoDB.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

$ne operator in MongoDB

Publish Date:2025/04/11 Views:84 Category:MongoDB

This article will discuss how the $ne operator works in MongoDB. In addition, we will list its differences from the $not operator. $ne operator in MongoDB $ne is an operator in MongoDB that stands for not equal to. This will compare the val

MongoDB $Set Operator

Publish Date:2025/04/11 Views:159 Category:MongoDB

With the help of this article, you will learn how to use $set the operator to partially update objects in MongoDB so that the new object overlaps/merges with the existing object. The $set operator replaces the value of a field with a given

Difference between $push and $addToSet in MongoDB

Publish Date:2025/04/11 Views:63 Category:MongoDB

This article explains the operators in MongoDB. What is the purpose of $push and $addToSet operators. Furthermore, the difference between these two operators is given in the code snippet. This article discusses the following topics. Operato

Counting records in MongoDB

Publish Date:2025/04/11 Views:146 Category:MongoDB

This article discusses operators in MongoDB, aggregation operators, and different ways to calculate the total number of records. Operations in MongoDB CRUD operations are a user interface concept that allows users to browse, search, and cha

Pretty printing in MongoDB

Publish Date:2025/04/11 Views:150 Category:MongoDB

This article will discuss how to use pretty printing in MongoDB to display formatted results. Pretty printing in MongoDB A cursor is an object that allows programmers in the Mongo world to iterate over documents in a Mongo collection. Altho

MongoDB Adding Elements to an Array

Publish Date:2025/04/11 Views:136 Category:MongoDB

This article will cover the various ways to add to an array in MongoDB. Adding to an array in MongoDB Use the $push operator to add values ​​to an array The $push operator is one of the various array update operators provided by MongoDB

MongoDB Search by ID

Publish Date:2025/04/11 Views:131 Category:MongoDB

The following article provides an overview of MongoDB find by Id() method. MongoDB provides a find by Id() function which can retrieve documents matching a user id. To use search by Id() in MongoDB, you need to use the find() function. If n

MongoDB starts with a query

Publish Date:2025/04/10 Views:195 Category:MongoDB

In this MongoDB article, users will learn how to start queries using $regex. It provides regular expression functionality for pattern matching strings in queries. MongoDB starts querying using $regex If you want to use $regex , use one of t

Export all collections in MongoDB

Publish Date:2025/04/10 Views:188 Category:MongoDB

This MongoDB tutorial will show you how to export all MongoDB collections. Most databases and language frameworks allow you to export data. This makes the data useful to other programs, applications, or languages ​​in various forms. CSV

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial