Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
-1for descending order (newest first) and1for ascending order (oldest first). - The
sort()method can be chained withfind()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.
Advertisements
