

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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") }
- Related Questions & Answers
- MongoDB find() query for nested document?
- Find oldest/ youngest post in MongoDB collection?
- MongoDB query to find records with keys containing dots?
- How to count number of keys in a MongoDB document?
- MongoDB query to update nested document
- MongoDB query to return only embedded document?
- MongoDB query to get last inserted document?
- MongoDB query to remove a specific document
- MongoDB query to remove subdocument from document?
- MongoDB query to update the nested document?
- Updating a MongoDB document and adding new keys only in the first document?
- MongoDB query for fields in embedded document?
- How to insert a document with date in MongoDB?
- MongoDB query to push document into an array
- Filter query on array of embedded document with MongoDB?
Advertisements