Sử dụng $subtract và $divide trong Aggregation
MongoDB lưu ngày tháng kiểu ISODate (milliseconds từ epoch). Trừ hai ngày cho độ chênh lệch milliseconds, chia cho mili-giây/ngày để ra số ngày.
Dữ liệu mẫu
> db.demo734.insertMany([
{ GivenDate: new ISODate("2020-01-10") },
{ GivenDate: new ISODate("2020-02-20") },
{ GivenDate: new ISODate("2010-12-01") },
{ GivenDate: new ISODate("2020-05-01") }
]);
Truy vấn Aggregation
db.demo734.aggregate([
{
$project: {
differenceMilli: { $subtract: [ new ISODate(), "$GivenDate" ] }
}
},
{
$project: {
differenceMilli: 1,
differenceindays: { $divide: ["$differenceMilli", 1000 * 60 * 60 * 24] }
}
}
]);
Kết quả (ví dụ chạy ngày 2020-04-15)
{ "_id": ..., "differenceMilli": NumberLong("9802234864"), "differenceindays": 113.45 }
{ "_id": ..., "differenceMilli": NumberLong("6259834864"), "differenceindays": 72.45 }
{ "_id": ..., "differenceMilli": NumberLong("297255034864"), "differenceindays": 3440.45 }
{ "_id": ..., "differenceMilli": NumberLong("125434864"), "differenceindays": 1.45 }
Lưu ý: new ISODate() trong aggregation đại diện cho thời điểm chạy truy vấn.