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

แปลง Date เป็น Timestamp ใน MongoDB

การแปลง Date (ISODate) เป็น Unix timestamp (milliseconds since epoch) ใน MongoDB ทำได้ด้วย $toLong ใน aggregate pipeline (MongoDB 4.0+)

สร้างคอลเลกชันและข้อมูลตัวอย่าง

> db.demo93.insertOne({"UserName":"Chris","ArrivalDate":new ISODate("2020-10-01")});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2d4b6479799acab037af68") }
> db.demo93.insertOne({"UserName":"David","ArrivalDate":new ISODate("2019-12-31")});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2d4b7379799acab037af69") }

แสดงข้อมูล

> db.demo93.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e2d4b6479799acab037af68"), "UserName" : "Chris", "ArrivalDate" : ISODate("2020-10-01T00:00:00Z") }
{ "_id" : ObjectId("5e2d4b7379799acab037af69"), "UserName" : "David", "ArrivalDate" : ISODate("2019-12-31T00:00:00Z") }

Query แปลง Date เป็น Timestamp

> db.demo93.aggregate([
...   { "$match": { "UserName": "Chris" }},
...   { "$addFields": {
...     "timestamp": { "$toLong": "$ArrivalDate" }
...   }}
... ]);

คำอธิบาย:

  • $match: กรองเฉพาะ UserName="Chris" ก่อนแปลง (ประหยัดทรัพยากร)
  • $toLong: "$ArrivalDate": แปลง ISODate เป็น milliseconds (Long/NumberLong)
  • $addFields: เพิ่ม field ใหม่ timestamp คง field เดิมไว้

ผลลัพธ์

{ "_id" : ObjectId("5e2d4b6479799acab037af68"), "UserName" : "Chris", "ArrivalDate" : ISODate("2020-10-01T00:00:00Z"), "timestamp" : NumberLong("1601510400000") }

1601510400000 ms = 2020-10-01 00:00:00 UTC ✓

Operator แปลงวันที่อื่นๆ

ตัวอย่าง $dateToString (format แบบกำหนดเอง)

db.demo93.aggregate([
  { $addFields: {
    dateStr: { $dateToString: { format: "%Y-%m-%d", date: "$ArrivalDate" } }
  }}
])
// ผลลัพธ์: "2020-10-01"

หมายเหตุ: Timestamp ใน MongoDB คือ milliseconds (ไม่ใช่ seconds เหมือน Unix timestamp ทั่วไป) ต้องหาร 1000 หากต้องการ seconds

Operatorคำอธิบาย
$toLongDate → milliseconds (Long)
$dateToStringDate → String (custom format)
$toDateString/Long → Date