- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements