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


To get the latest set of data from data records, use sort() and -1. For only a single data i.e. document, use LIMIT(1). Let us create a collection with documents −

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

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

> db.demo521.find();

This will produce the following output −

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

Following is the query to get the latest set of data based on the date −

> db.demo521.find().sort({"PurchaseDate": -1}).limit(1);

This will produce the following output −

{ "_id" : ObjectId("5e89a1b9b3fbf26334ef6118"), "PurchaseDate" : ISODate("2020-04-05T00:00:00Z"), "ProductName" : "Product-10" }

Updated on: 13-May-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements