How to get latest set of data from a MongoDB collection based on the date records?

To get the latest set of data from MongoDB collection based on date records, use sort() with -1 for descending order. For a single latest document, combine with limit(1).

Syntax

// Get all records sorted by date (latest first)
db.collection.find().sort({"dateField": -1});

// Get only the latest record
db.collection.find().sort({"dateField": -1}).limit(1);

Sample Data

db.demo521.insertMany([
    {"PurchaseDate": new ISODate("2019-01-10"), "ProductName": "Product-1"},
    {"PurchaseDate": new ISODate("2020-04-05"), "ProductName": "Product-10"},
    {"PurchaseDate": new ISODate("2010-05-08"), "ProductName": "Product-4"},
    {"PurchaseDate": new ISODate("2020-02-21"), "ProductName": "Product-3"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e89a1acb3fbf26334ef6117"),
        ObjectId("5e89a1b9b3fbf26334ef6118"),
        ObjectId("5e89a1c8b3fbf26334ef6119"),
        ObjectId("5e89a1d7b3fbf26334ef611a")
    ]
}

View All Documents

db.demo521.find();
{ "_id": ObjectId("5e89a1acb3fbf26334ef6117"), "PurchaseDate": ISODate("2019-01-10T00:00:00Z"), "ProductName": "Product-1" }
{ "_id": ObjectId("5e89a1b9b3fbf26334ef6118"), "PurchaseDate": ISODate("2020-04-05T00:00:00Z"), "ProductName": "Product-10" }
{ "_id": ObjectId("5e89a1c8b3fbf26334ef6119"), "PurchaseDate": ISODate("2010-05-08T00:00:00Z"), "ProductName": "Product-4" }
{ "_id": ObjectId("5e89a1d7b3fbf26334ef611a"), "PurchaseDate": ISODate("2020-02-21T00:00:00Z"), "ProductName": "Product-3" }

Example: Get Latest Record

Get the single most recent document based on PurchaseDate ?

db.demo521.find().sort({"PurchaseDate": -1}).limit(1);
{ "_id": ObjectId("5e89a1b9b3fbf26334ef6118"), "PurchaseDate": ISODate("2020-04-05T00:00:00Z"), "ProductName": "Product-10" }

Example: Get Latest 2 Records

db.demo521.find().sort({"PurchaseDate": -1}).limit(2);
{ "_id": ObjectId("5e89a1b9b3fbf26334ef6118"), "PurchaseDate": ISODate("2020-04-05T00:00:00Z"), "ProductName": "Product-10" }
{ "_id": ObjectId("5e89a1d7b3fbf26334ef611a"), "PurchaseDate": ISODate("2020-02-21T00:00:00Z"), "ProductName": "Product-3" }

Conclusion

Use sort({"dateField": -1}) to order documents by date in descending order, showing latest first. Combine with limit() to restrict the number of results returned.

Updated on: 2026-03-15T03:22:23+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements