ใช้ $dateFromParts สร้าง Date Object จากส่วนประกอบ แล้ว $dateToString จัดรูปแบบสตริง
ตัวอย่างข้อมูลทดสอบ
> db.demo386.insert({details: {Month: 02, Day: 27, Year: 2020}});
แสดงข้อมูล
> db.demo386.find();
{
"_id" : ObjectId("5e5bd9a222064be7ab44e7f7"),
"details" : { "Month" : 2, "Day" : 27, "Year" : 2020 }
}
คำสั่ง Aggregation แปลงเป็นวันที่
> db.demo386.aggregate({
"$project":{
"_id":0,
"DueDate":{
"$dateToString":{
"format":"%m-%d-%Y",
"date":{
"$dateFromParts": {
"year":"$details.Year",
"month":"$details.Month",
"day":"$details.Day"
}
}
}
}
}
});
ผลลัพธ์
{ "DueDate" : "02-27-2020" }
รูปแบบ Format หลัก:
%Yปี 4 หลัก,%mเดือน 2 หลัก,%dวัน 2 หลัก%Hชั่วโมง (24h),%Mนาที,%Sวินาที%Lมิลลิวินาที
หมายเหตุ: $dateFromParts ต้องการ year, month, day เป็นตัวเลข (หรือสตริงที่แปลงได้)