Để lưu trữ ngày tháng trong MongoDB, **luôn dùng kiểu BSON Date (ISODate)** thay vì String. MongoDB shell cung cấp new Date() hoặc ISODate() (alias). Kiểu Date hỗ trợ so sánh, range query, aggregation date operators, timezone, và index hiệu quả.
1. Các cách chèn Date
> db.demo421.insert({ "DueDate": new Date(Date.now()) }); // Thời điểm hiện tại
> db.demo421.insert({ "DueDate": new Date("2020-01-15") }); // Parse ISO string (UTC)
> db.demo421.insert({ "DueDate": new Date("2018-12-31") }); // Parse ISO string
> // Hoặc dùng ISODate() (shell helper)
> db.demo421.insert({ "DueDate": ISODate("2020-01-15T10:30:00Z") });
2. Xem dữ liệu (lưu trữ sebagai ISODate UTC)
> db.demo421.find();
Kết quả:
{ "_id": ObjectId("..."), "DueDate": ISODate("2020-03-19T16:50:52.746Z") } // now
{ "_id": ObjectId("..."), "DueDate": ISODate("2020-01-15T00:00:00Z") } // 2020-01-15
{ "_id": ObjectId("..."), "DueDate": ISODate("2018-12-31T00:00:00Z") } // 2018-12-31
Lưu ý quan trọng:
- MongoDB lưu Date **luôn là UTC**. Input string không timezone (như "2020-01-15") được hiểu là UTC 00:00.
- Để lưu múi giờ cụ thể:
new Date("2020-01-15T10:30:00+07:00")(ISO 8601 với offset). - Trong Driver (Node.js, Python, Java...): Truyền native Date object của ngôn ngữ, driver tự convert sang BSON Date.
- **KHÔNG** lưu dưới dạng String ("2020-01-15") -> mất khả năng query range, sort, index hiệu quả.
Query ví dụ: find({ DueDate: { $gte: ISODate("2020-01-01"), $lt: ISODate("2020-02-01") } }).