Để lưu ngày giờ hiện tại hoặc ngày giờ cụ thể trong MongoDB, bạn sử dụng new ISODate() (hoặc new Date() - tương đương trong shell). MongoDB lưu trữ kiểu BSON Date (64-bit integer milliseconds từ epoch UTC).
Tạo document với ISODate
Hiển thị document:
{ "_id" : ObjectId("5cbd67d4de8cc557214c0e04"), "UserName" : "John", "UserLoginDatetime" : ISODate("2018-01-31T12:34:56Z") } { "_id" : ObjectId("5cbd67e8de8cc557214c0e05"), "UserName" : "John", "UserLoginDatetime" : ISODate("2019-02-01T04:01:10Z") } { "_id" : ObjectId("5cbd6805de8cc557214c0e06"), "UserName" : "John", "UserLoginDatetime" : ISODate("2019-04-22T12:36:45Z") }Các cách tạo Date trong MongoDB
new ISODate()- Ngày giờ hiện tại (UTC)new ISODate('2024-01-15')- Ngày cụ thể (UTC)new ISODate('2024-01-15T10:30:00Z')- Ngày giờ UTC cụ thểnew Date()- Tương đương ISODate() trong shellISODate()(không new) - Cũng hoạt động trong shell
Lưu ý quan trọng
- MongoDB luôn lưu trữ UTC. Múi giờ chỉ áp dụng khi hiển thị/đọc
- Chuỗi ISO 8601:
YYYY-MM-DDTHH:mm:ss.sssZ(Z = UTC) - Trong driver: Dùng native Date object của ngôn ngữ (JavaScript Date, Java Date, Python datetime, v.v.)
- Query range:
{date: {$gte: ISODate("2024-01-01"), $lt: ISODate("2024-02-01")}}