Tính tuổi từ DateOfBirth dùng $subtract và $divide
Trừ ngày hiện tại (new Date()) cho ngày sinh, chia cho mili-giây trong một năm (365 ngày).
Dữ liệu mẫu
> db.demo754.insertMany([
{ DateOfBirth: new Date("2000-05-03") },
{ DateOfBirth: new Date("2010-01-21") },
{ DateOfBirth: new Date("2018-05-03") }
]);
Truy vấn Aggregation
db.demo754.aggregate([
{
$project: {
date: "$DateOfBirth",
StudentAge: {
$divide: [
{ $subtract: [new Date(), "$DateOfBirth"] },
365 * 24 * 60 * 60 * 1000
]
}
}
}
]);
Kết quả (ví dụ chạy năm 2020)
{ "_id": ObjectId("..."), "date": ISODate("2000-05-03T00:00:00Z"), "StudentAge": 20.01 }
{ "_id": ObjectId("..."), "date": ISODate("2010-01-21T00:00:00Z"), "StudentAge": 10.29 }
{ "_id": ObjectId("..."), "date": ISODate("2018-05-03T00:00:00Z"), "StudentAge": 2.00 }
Kết quả là tuổi gần đúng (số thực). Để làm tròn xuống tuổi tròn, có thể dùng $floor.