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

แปลง ObjectId เป็น String ใน MongoDB

การแปลง ObjectId ให้เป็น String

วิธีมาตรฐานคือใช้ $toString ใน aggregation pipeline (MongoDB 4.0+)

ตัวอย่างข้อมูล

สร้างคอลเลกชัน objectidToStringDemo เหมือนบทความก่อนหน้า

Aggregation Query

> db.objectidToStringDemo.aggregate([
    {$project: {
        _id: {$toString: "$_id"}
    }}
]);

ผลลัพธ์:

{ "_id" : "5c92b80036de59bd9de0639d" }
{ "_id" : "5c92b80436de59bd9de0639e" }
{ "_id" : "5c92b80936de59bd9de0639f" }
{ "_id" : "5c92b81836de59bd9de063a0" }

กรณี MongoDB เวอร์ชันเก่า

ก่อนมี $toString ใช้วิธี _id.str ใน JavaScript หรือ _id.valueOf() แต่แนะนำให้อัปเกรดและใช้ $toString แทน

การใช้งานใน Application

ในโปรแกรม (Node.js, Python, Java) ไดรเวอร์มักมีเมธอดแปลง ObjectId เป็น String โดยตรง เช่น objectId.toString() หรือ str(objectId)