Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

อัปเดต Timestamp ให้เป็น Current Date ใน MongoDB

การอัปเดต Timestamp เป็นวันที่ปัจจุบัน

เพื่ออัปเดต ให้ใช้ update() ใน MongoDB เพื่อตั้งค่าเป็นวันที่ปัจจุบัน ต้องดึงวันที่ปัจจุบันก่อน:

var todayDate = new Date();

สร้าง Collection พร้อมข้อมูล

> db.demo644.insertOne({"ShippingDate":new ISODate("2018-04-19")});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9c76896c954c74be91e6e6") }
> db.demo644.insertOne({"ShippingDate":new ISODate("2019-01-10")});
{ "acknowledged" : true, "insertedId" : ObjectId("5e9c76966c954c74be91e6e7") }

แสดงเอกสารทั้งหมด

> db.demo644.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e9c76896c954c74be91e6e6"), "ShippingDate" : ISODate("2018-04-19T00:00:00Z") }
{ "_id" : ObjectId("5e9c76966c954c74be91e6e7"), "ShippingDate" : ISODate("2019-01-10T00:00:00Z") }

คิวรีอัปเดต Timestamp

> var todayDate = new Date();
> todayDate.setHours(todayDate.getHours() + 1);
1587315898453
> db.demo644.update({}, {$set: {ShippingDate:todayDate}}, {multi: true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

แสดงเอกสารหลังอัปเดต

> db.demo644.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e9c76896c954c74be91e6e6"), "ShippingDate" : ISODate("2020-04-19T17:04:58.453Z") }
{ "_id" : ObjectId("5e9c76966c954c74be91e6e7"), "ShippingDate" : ISODate("2020-04-19T17:04:58.453Z") }