- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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") }
Advertisements