在 MongoDB 中儲存日期/時間最佳途徑?
有兩種不同的方式可以將日期/時間儲存在 MongoDB 中。在第一種方法中,你可以像使用 JavaScript 那樣使用 Date 物件。Date 物件是將日期/時間儲存在 MongoDB 中的最佳方式。語法如下
new Date();
在第二種方法中,你可以使用 ISODate()。語法如下
new ISODate();
為了理解以上語法,我們使用遵循第一種方法的文件建立一個集合。建立帶有文件的集合的查詢如下
第一種方法
> db.ProductsInformation.insertOne({"ProductId":"Product-1","ProductDeliveryDateTime":new Date()}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ec6786fd07954a4890686") }
第二種方法
> db.ProductsInformation.insertOne({"ProductId":"Product-2","ProductDeliveryDateTime":new ISODate()}); { "acknowledged" : true, "insertedId" : ObjectId("5c6ec6846fd07954a4890687") }
使用 find() 方法從集合中顯示所有文件。查詢如下
> 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") }
注意:儲存日期/時間物件的最佳方式是使用 Date 物件。
廣告