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

กำลังแปลงสตริงเป็นวันที่ใน MongoDB หรือไม่


ในการแปลงสตริงเป็นวันที่ใน MongoDB ให้ใช้ไวยากรณ์ต่อไปนี้:

db.yourCollectionName.aggregate([ { $project:{ anyVariableName:{ $dateFromString:{ dateString:'$yourFieldName' } } } } ]);

เพื่อให้เข้าใจไวยากรณ์ข้างต้น ให้เราสร้างคอลเลกชันพร้อมเอกสารบางส่วน แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้:

> db.ConvertStringToDateDateDemo.insertOne({"ArrivalDate":"20-10-2019"});{ "acknowledged" :true, "insertedId" :ObjectId("5c6ef3596fd07954a489069f")}> db.ConvertStringToDateDemo.insertOne( {"ArrivalDate":"21-02-2019"});{ "acknowledged" :true, "insertedId" :ObjectId("5c6ef3616fd07954a48906a0")}> db.ConvertStringToDateDateDemo.insertOne({"ArrivalDate":"10-12- 2018"});{ "รับทราบ" :จริง "insertedId" :ObjectId("5c6ef36d6fd07954a48906a1")}> db.ConvertStringToDateDateDemo.insertOne({"ArrivalDate":"31-01-2017"});{ "รับทราบ" :จริง "insertedId" :ObjectId("5c6ef37b6fd07954a48906a2")}

แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้เมธอด find() แบบสอบถามมีดังนี้:

> db.ConvertStringToDateDemo.find().pretty();

ต่อไปนี้เป็นผลลัพธ์:

{ "_id" :ObjectId("5c6ef3596fd07954a489069f"), "ArrivalDate" :"20-10-2019"}{ "_id" :ObjectId("5c6ef3616fd07954a48906a0"), "ArrivalDate" :"21-02-2019" }{ "_id" :ObjectId("5c6ef36d6fd07954a48906a1"), "ArrivalDate" :"10-12-2018"}{ "_id" :ObjectId("5c6ef37b6fd07954a48906a2"), "ArrivalDate" } <31-01-2017" /pre> 

นี่คือข้อความค้นหาที่จะแปลงสตริงเป็นวันที่:

> db.ConvertStringToDateDateDemo.aggregate( [ {... $project:{... StringToDate:{... $dateFromString:{... dateString:'$ArrivalDate'... }... } .. }... } ] ).pretty();

ต่อไปนี้เป็นผลลัพธ์:

{ "_id" :ObjectId("5c6ef3596fd07954a489069f"), "StringToDate" :ISODate("2019-10-20T00:00:00Z")}{ "_id" :ObjectId("5c6ef3616fd07954a48906a0"), "StringToDate" ISODate("2019-02-21T00:00:00Z")}{ "_id" :ObjectId("5c6ef36d6fd07954a48906a1"), "StringToDate" :ISODate("2018-12-10T00:00:00Z")}{ "_id" :ObjectId("5c6ef37b6fd07954a48906a2"), "StringToDate" :ISODate("2017-01-31T00:00:00Z")}