MongoDB 4.0+ มี operator $toObjectId สำหรับแปลง string ที่เป็น ObjectId hex string 24 ตัวอักษร ให้กลายเป็น ObjectId จริง ใช้ใน aggregate pipeline
สร้างคอลเลกชันและข้อมูลตัวอย่าง
> db.demo95.insertOne({"Id":"5ab9cbe531c2ab715d42129a"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e2d5ef5b8903cdd865577ac") }
แสดงข้อมูล
> db.demo95.find();
ผลลัพธ์:
{ "_id" : ObjectId("5e2d5ef5b8903cdd865577ac"), "Id" : "5ab9cbe531c2ab715d42129a" }
Query แปลง String เป็น ObjectId
> db.demo95.aggregate([
{ "$addFields": { "d" : { "$toObjectId": "$Id" } }}
])
ผลลัพธ์
{ "_id" : ObjectId("5e2d5ef5b8903cdd865577ac"), "Id" : "5ab9cbe531c2ab715d42129a", "d" : ObjectId("5ab9cbe531c2ab715d42129a") }
คำอธิบาย:
$addFields: เพิ่ม field ใหม่ โดยคง field เดิมไว้$toObjectId: "$Id": แปลงค่า field Id (string) เป็น ObjectId- field ใหม่ชื่อ "d" จะเป็น ObjectId เดียวกับค่า string เดิม
Operator แปลงชนิดข้อมูลอื่นๆ (Type Conversion)
MongoDB 4.0+ มี operators เหมือนกันสำหรับชนิดข้อมูลต่างๆ:
| Operator | แปลงเป็น |
|---|---|
$toObjectId | ObjectId |
$toString | String |
$toInt / $toLong | Integer / Long |
$toDouble | Double |
$toBool | Boolean |
$toDate | Date |
$toDecimal | Decimal128 |