Find oldest/ youngest post in MongoDB collection?


To find oldest/youngest post in MongoDB collection, you can use sort(). Let’s say you have a document with a field “UserPostDate” and you need to get the oldest and youngest post. For that, Let us first create a collection with documents

>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Larry@123","UserName":"Larry","UserPostDate":new ISODate('2019-03-27 12:00:00')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a700f15e86fd1496b38ab")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Sam@897","UserName":"Sam","UserPostDate":new ISODate('2012-06-17 11:40:30')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a703815e86fd1496b38ac")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"David@777","UserName":"David","UserPostDate":new ISODate('2018-01-31 10:45:35')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a705e15e86fd1496b38ad")
}
>db.getOldestAndYoungestPostDemo.insertOne({"UserId":"Chris@909","UserName":"Chris","UserPostDate":new ISODate('2017-04-14 04:12:04')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9a708915e86fd1496b38ae")
}

Following is the query to display all documents from a collection with the help of find() method

> db.getOldestAndYoungestPostDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9a700f15e86fd1496b38ab"),
   "UserId" : "Larry@123",
   "UserName" : "Larry",
   "UserPostDate" : ISODate("2019-03-27T12:00:00Z")
}
{
   "_id" : ObjectId("5c9a703815e86fd1496b38ac"),
   "UserId" : "Sam@897",
   "UserName" : "Sam",
   "UserPostDate" : ISODate("2012-06-17T11:40:30Z")
}
{
   "_id" : ObjectId("5c9a705e15e86fd1496b38ad"),
   "UserId" : "David@777",
   "UserName" : "David",
   "UserPostDate" : ISODate("2018-01-31T10:45:35Z")
}
{
   "_id" : ObjectId("5c9a708915e86fd1496b38ae"),
   "UserId" : "Chris@909",
   "UserName" : "Chris",
   "UserPostDate" : ISODate("2017-04-14T04:12:04Z")
}

Following is the query to find oldest post in MongoDB collection

> db.getOldestAndYoungestPostDemo.find().sort({ "UserPostDate" : 1 }).limit(1);

This will produce the following output

{ "_id" : ObjectId("5c9a703815e86fd1496b38ac"), "UserId" : "Sam@897", "UserName" : "Sam", "UserPostDate" : ISODate("2012-06-17T11:40:30Z") }

Following is the query to find the youngest (recent) post in MongoDB collection

> db.getOldestAndYoungestPostDemo.find().sort({ "UserPostDate" : -1 }).limit(1);

This will produce the following output

{ "_id" : ObjectId("5c9a700f15e86fd1496b38ab"), "UserId" : "Larry@123", "UserName" : "Larry", "UserPostDate" : ISODate("2019-03-27T12:00:00Z") }

Updated on: 30-Jul-2019

792 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements