Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert birth date records to age with MongoDB
To convert birth date records to age in MongoDB, use the $dateDiff operator or calculate the difference between the current date and birth date using $subtract and $divide operators in an aggregation pipeline.
Syntax
db.collection.aggregate([
{
$project: {
age: {
$divide: [
{ $subtract: [new Date(), "$birthDateField"] },
(365 * 24 * 60 * 60 * 1000)
]
}
}
}
]);
Sample Data
db.demo754.insertMany([
{ "DateOfBirth": new Date("2000-05-03") },
{ "DateOfBirth": new Date("2010-01-21") },
{ "DateOfBirth": new Date("2018-05-03") }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5eae9b2da930c785c834e56f"),
ObjectId("5eae9b34a930c785c834e570"),
ObjectId("5eae9b3da930c785c834e571")
]
}
Display all documents from the collection ?
db.demo754.find();
{ "_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") }
Example: Convert Birth Date to Age
db.demo754.aggregate([
{
$project: {
date: "$DateOfBirth",
StudentAge: {
$divide: [
{ $subtract: [new Date(), "$DateOfBirth"] },
(365 * 24 * 60 * 60 * 1000)
]
}
}
}
]);
{ "_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 }
How It Works
-
$subtractcalculates the difference between current date and birth date in milliseconds -
$divideconverts milliseconds to years by dividing by milliseconds per year - The formula
(365 * 24 * 60 * 60 * 1000)represents milliseconds in a year
Conclusion
Use the $subtract and $divide operators in an aggregation pipeline to convert birth dates to age. This method calculates the precise age difference in years as decimal values.
Advertisements
