การแปลง 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 แปลงวันที่อื่นๆ
| Operator | คำอธิบาย |
|---|---|
$toLong | Date → milliseconds (Long) |
$dateToString | Date → String (custom format) |
$toDate | String/Long → Date |