MongoDB x Golang Start to Max
มาต่อกันเด้อกับการใช้งาน MongoDB กับ Golang. Let’s go…
ก่อนทำการเริ่มต้น ถ้าใครยังไม่เคยติดตั้ง MongoDB ใน Docker สามารถดูจากลิ้งด้านล่างนี้ได้เลยครับ ^_^
เริ่มกันได้แวววววววววววว……
Step1. สร้างโปรเจค Golang เพื่อ connect MongoDB ในเครื่อง
Step 2 : เขียนโค๊ด คำสั่งโชว์ Database
result:
[admin animal config local mydbone]
Step 3. เพิ่ม struct ใน code ตัวอย่างจะเป็น Customer
Step 4. เขียนโค๊ดคำสั่ง insert (assign ค่าให้ struct ที่เรากำหนดไว้เพื่อทดสอบการ insert ข้อมูล)
result :
Inserted a single document: ObjectID("608226c3faf816ce2b8d1191")
Step 5 : ทำการ insert ในรูปแบบของ Array ใน function main() ให้ call function insertMany(client)
result :
Inserted multiple document: [ObjectID("6082277af5641256632aed6f") ObjectID("6082277af5641256632aed70") ObjectID("6082277af5641256632aed71")]
Step 6 : คำสั่งค้นหาข้อมูลโดย collection.Find()
ใน function main() ให้ call function find(client)
result :
{Max Smart 10}
{Max4 Smart4 40}
{Max5 Smart5 50}
{Max6 Smart6 60}
Found multiple documents (array of pointers): [0xc0003a23f0 0xc0003a2510 0xc0003a2570 0xc0003a25d0]
คำสั่งค้นหาข้อมูลโดย collection.FindOne()
ใน function main() ให้ call function findOne(client)
result :
Found a single document: {Fistname:Max5 Lastname:Smart5 Age:50}
Step 7 : คำสั่ง collection.UpdateOne()
. ใน function main() ให้ call function updateOne(client)
result :
Matched 1 documents and updated 1 documents.
Step 8 : คำสั่ง collection.UpdateMany()
. ใน function main() ให้ call function updateMany(client)
Step 9 : คำสั่ง collection.DeleteMany()
. ใน function main() ให้ call function deleteMany(client)
result :
Deleted 1 documents in the trainers collection
เป็นอย่างไรกันบ้างครับ กับการเริ่มต้นเขียน Golang เพื่อเชื่อมต่อกับ MongoDB หวังว่าจะมีประโยชน์ไม่มากก็น้อยสำหรับคนที่สนใจนะครับ
บ่ายบาย……..แล้วพบกันใหม่