MongoDB query to find oldest date of three keys in each document

MongoDBDatabaseBig Data Analytics

To find the oldest date, use $min in MongoDB aggregate(). Let us create a collection with documents −

> db.demo353.insertOne({"Date1":new ISODate("2019-01-10"),"Date2":new ISODate("2016-01-21"),"Date3":new ISODate("2020-04-11")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e568261f8647eb59e5620be")
}
> db.demo353.insertOne({"Date1":new ISODate("2011-11-20"),"Date2":new ISODate("2013-12-10"),"Date3":new ISODate("2014-01-05")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e56827ff8647eb59e5620bf")
}

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

> db.demo353.find();

This will produce the following output −

{ "_id" : ObjectId("5e568261f8647eb59e5620be"), "Date1" : ISODate("2019-01-10T00:00:00Z"), "Date2" : ISODate("2016-01-21T00:00:00Z"), "Date3" : ISODate("2020-04-11T00:00:00Z") }
{ "_id" : ObjectId("5e56827ff8647eb59e5620bf"), "Date1" : ISODate("2011-11-20T00:00:00Z"), "Date2" : ISODate("2013-12-10T00:00:00Z"), "Date3" : ISODate("2014-01-05T00:00:00Z") }

Following is the query to find the oldest date in each document −

> db.demo353.aggregate([
...    {
...       $project: {
...          OldestDate: {
...             $min: [
...                { $ifNull: [ "$Date1", new Date() ] },
...                { $ifNull: [ "$Date2", new Date() ] },
...                { $ifNull: [ "$Date3", new Date() ] },
...             ]
...          }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : ObjectId("5e568261f8647eb59e5620be"), "OldestDate" : ISODate("2016-01-21T00:00:00Z") }
{ "_id" : ObjectId("5e56827ff8647eb59e5620bf"), "OldestDate" : ISODate("2011-11-20T00:00:00Z") }
raja
Updated on 02-Apr-2020 08:04:33

Advertisements