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

แปลงส่วนประกอบวันที่ (วัน เดือน ปี) ให้เป็น Date ใน MongoDB

ใช้ $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 เป็นตัวเลข (หรือสตริงที่แปลงได้)