Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to find oldest date of three keys in each document
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") }Advertisements