How to convert birth date records to age with MongoDB


Let us create a collection with documents −

> db.demo754.insertOne({"DateOfBirth":new Date("2000-05-03")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae9b2da930c785c834e56f")
}
> db.demo754.insertOne({"DateOfBirth":new Date("2010-01-21")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae9b34a930c785c834e570")
}
> db.demo754.insertOne({"DateOfBirth":new Date("2018-05-03")});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5eae9b3da930c785c834e571")
}

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

> db.demo754.find();

This will produce the following output −

{ "_id" : ObjectId("5eae9b2da930c785c834e56f"), "DateOfBirth" : ISODate("2000-05-03T00:00:00Z") }
{ "_id" : ObjectId("5eae9b34a930c785c834e570"), "DateOfBirth" : ISODate("2010-01-21T00:00:00Z") }
{ "_id" : ObjectId("5eae9b3da930c785c834e571"), "DateOfBirth" : ISODate("2018-05-03T00:00:00Z") }

Following is the query to convert date of birth to age −

> db.demo754.aggregate( [ {
...    $project: {
...       date:"$DateOfBirth",
...          StudentAge: {
...             $divide: [{$subtract: [ new Date(), "$DateOfBirth" ] },
...             (365 * 24*60*60*1000)]
...          }
...       }
... } ] )

This will produce the following output −

{ "_id" : ObjectId("5eae9b2da930c785c834e56f"), "date" : ISODate("2000-05-03T00:00:00Z"), "StudentAge" : 20.014896543093606 }
{ "_id" : ObjectId("5eae9b34a930c785c834e570"), "date" : ISODate("2010-01-21T00:00:00Z"), "StudentAge" : 10.288869145833333 }
{ "_id" : ObjectId("5eae9b3da930c785c834e571"), "date" : ISODate("2018-05-03T00:00:00Z"), "StudentAge" : 2.003937638984018 }

Updated on: 01-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements