มี 2 วิธีหลักในการจัดเก็บ Date/Time ใน MongoDB:
วิธีที่ 1: ใช้ Date Object ของ JavaScript (แนะนำ)
new Date();
วิธีที่ 2: ใช้ ISODate()
new ISODate();
ตัวอย่างทั้งสองวิธี
// วิธี 1: Date object
> db.ProductsInformation.insertOne({"ProductId":"Product-1","ProductDeliveryDateTime": new Date()});
{ "acknowledged" : true, "insertedId" : ObjectId("5c6ec6786fd07954a4890686") }
// วิธี 2: ISODate
> db.ProductsInformation.insertOne({"ProductId":"Product-2","ProductDeliveryDateTime": new ISODate()});
{ "acknowledged" : true, "insertedId" : ObjectId("5c6ec6846fd07954a4890687") }
แสดงผลลัพธ์
> db.ProductsInformation.find().pretty();
{ "_id" : ObjectId("5c6ec6786fd07954a4890686"), "ProductId" : "Product-1", "ProductDeliveryDateTime" : ISODate("2019-02-21T15:40:40.901Z") }
{ "_id" : ObjectId("5c6ec6846fd07954a4890687"), "ProductId" : "Product-2", "ProductDeliveryDateTime" : ISODate("2019-02-21T15:40:52.684Z") }
สรุป: ทั้งสองวิธีเก็บข้อมูลเป็น BSON Date (UTC) เท่ากัน แต่ Date Object เป็น Best Practice เนื่องเป็น Native JavaScript Type รองรับ Method ต่างๆ ของ Date ได้ครบถ้วน และทำงานร่วมกับ Driver ต่างๆ ได้ดีที่สุด