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

วิธีแปลง ObjectId เป็นสตริงใน MongoDB


ในการแปลง ObjectId เป็นสตริง ให้ใช้ $toString ใน MongoDB เพื่อให้เข้าใจแนวคิดข้างต้น ให้เราสร้างคอลเลกชันพร้อมกับเอกสาร แบบสอบถามเพื่อสร้างคอลเลกชันที่มีเอกสารมีดังนี้ -

> db.objectidToStringDemo.insertOne({"UserName":"John"});{ "acknowledged" :true, "insertedId" :ObjectId("5c92b80036de59bd9de0639d")}> db.objectidToStringDemo.insertOne({"ชื่อผู้ใช้" :"Chris"});{ "acknowledged" :true, "insertedId" :ObjectId("5c92b80436de59bd9de0639e")}> db.objectidToStringDemo.insertOne({"UserName":"Larry"});{ "acknowledged" :true, "insertedId" :ObjectId("5c92b80936de59bd9de0639f")}> db.objectidToStringDemo.insertOne({"UserName":"Robert"});{ "acknowledged" :true, "insertedId" :ObjectId("5c92b818depreapreapd")> 

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

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

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

{ "_id" :ObjectId("5c92b80036de59bd9de0639d"), "UserName" :"John" }{ "_id" :ObjectId("5c92b80436de59bd9de0639e"), "UserName" :"Chris" }{ "_id" :ObjectId( "5c92b80936de59bd9de0639f"), "ชื่อผู้ใช้" :"Larry" }{ "_id" :ObjectId("5c92b81836de59bd9de063a0"), "ชื่อผู้ใช้" :"Robert" }

นี่คือแบบสอบถามเพื่อแปลง ObjectId เป็นค่าสตริงใน MongoDB รวม แบบสอบถามมีดังต่อไปนี้ −

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

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

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