Để chuyển đổi ISODate sang giá trị số (timestamp - milliseconds từ epoch 1970-01-01 UTC) trong MongoDB shell, bạn sử dụng phương thức getTime() của đối tượng Date.
Cú pháp
> var arrivalDate=ISODate('2019-04-18 13:50:45');
Chuyển sang số (milliseconds):
> new Date(1555595445000);
ISODate("2019-04-18T13:50:45Z")
Kết quả khớp với ISODate ban đầu.
Ứng dụng thực tế
- Lưu trữ: MongoDB lưu ISODate là BSON Date (64-bit integer milliseconds)
- So sánh: Số dễ so sánh, tính toán khoảng thời gian
- Tương tác: Nhiều ngôn ngữ/client driver trả về timestamp số thay vì object Date
- Aggregation: Dùng
$toLong(MongoDB 4.0+) trong pipeline:{$project: {timestamp: {$toLong: "$dateField"}}}
Lưu ý: getTime() trả về milliseconds. Để có seconds (như Unix timestamp), chia cho 1000: Math.floor(arrivalDate.getTime() / 1000).