How to order by timestamp (descending order) in MongoDB

To order by timestamp in descending order in MongoDB, use the sort() method with the timestamp field set to -1. This arranges documents from newest to oldest timestamp.

Syntax

db.collection.find().sort({"timestamp": -1});

Create Sample Data

Let us create a collection with timestamp documents ?

db.demo737.insertMany([
    {"timestamp": new ISODate("2020-04-01")},
    {"timestamp": new ISODate("2020-10-31")},
    {"timestamp": new ISODate("2020-05-02")}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5ead682157bb72a10bcf065c"),
        ObjectId("5ead682757bb72a10bcf065d"),
        ObjectId("5ead682a57bb72a10bcf065e")
    ]
}

Display Sample Data

Display all documents from the collection ?

db.demo737.find();
{ "_id": ObjectId("5ead682157bb72a10bcf065c"), "timestamp": ISODate("2020-04-01T00:00:00Z") }
{ "_id": ObjectId("5ead682757bb72a10bcf065d"), "timestamp": ISODate("2020-10-31T00:00:00Z") }
{ "_id": ObjectId("5ead682a57bb72a10bcf065e"), "timestamp": ISODate("2020-05-02T00:00:00Z") }

Order by Timestamp (Descending)

Query to order by timestamp in descending order ?

db.demo737.find().sort({"timestamp": -1});
{ "_id": ObjectId("5ead682757bb72a10bcf065d"), "timestamp": ISODate("2020-10-31T00:00:00Z") }
{ "_id": ObjectId("5ead682a57bb72a10bcf065e"), "timestamp": ISODate("2020-05-02T00:00:00Z") }
{ "_id": ObjectId("5ead682157bb72a10bcf065c"), "timestamp": ISODate("2020-04-01T00:00:00Z") }

Key Points

  • Use -1 for descending order (newest first) and 1 for ascending order (oldest first).
  • The sort() method can be chained with find() to sort query results.

Conclusion

Use sort({"timestamp": -1}) to order MongoDB documents by timestamp in descending order. The -1 value ensures the newest timestamps appear first in the results.

Updated on: 2026-03-15T03:53:31+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements