How to order by timestamp (descending order) in MongoDB


To order by timestamp, use sort() in MongoDB. Let us create a collection with documents −

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

Display all documents from a collection with the help of find() method −

> db.demo737.find();

This will produce the following output −

{ "_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") }

Following is the query to order by timestamp (descending order) −

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

This will produce the following output −

{ "_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") }

Updated on: 30-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements