Mongo db อย่างโปร ตอน CRUD Operations

KhunGames
SkillLane
Published in
2 min readJul 17, 2018

Create Operations

Create หรือ insert operation คือคำสั่งในการสร้าง documents ใหม่ไปยัง collection . ถ้า collection ยังไม่ถูกสร้าง insert operations จะสร้าง collection นั้นขึ้นมาให้.

ใน MongoDB มี methods insert ดังต่อไปนี้

ใน MongoDB, insert operations จะมีผลกับ collection เดียวเท่านั้น. ทุกๆ write operations ใน MongoDB ที่กระทำกับ single document จะเป็น atomic เสมอ.

นอกจากนี้ยังมีคำสั่งอื่นๆที่ทำหน้าที่คล้ายๆกับ insert เช่น update โดยใส่ upsert หรือ collection.save()

อ่านเพิ่มเติม Insert Documents.

Read Operations

Read operations คือคำสั่งที่จะดึง documents จาก collection ที่เราต้องการ.

ใน MongoDB มี methods read ดังต่อไปนี้

ซึ่งเราสามารถใส่ query filters or criteria เพื่อหา document ตามเงื่อนไขที่เราต้องการ

ถ้าเราใช้ aggregate เราจะสามารถ ดึง ข้อมูลจากหลาย collection พร้อมกันได้ด้วย คำสั่ง $lookup

อ่านเพิ่มเติม:

Update Operations

Update operations จะทำการแก้ไข documents ที่อยู่ใน collection.

ใน MongoDB มี methods update ดังต่อไปนี้

ใน MongoDB, update operations จะมีผลกับ collection เดียวเท่านั้น. ทุกๆ update operations ใน MongoDB ที่กระทำกับ single document จะเป็น atomic เสมอ.

ซึ่งเราสามารถใส่ filters เพื่อหา document ตามเงื่อนไขที่เราต้องการ โดยส่วนใหญ่จะใช้ syntax เดียวกันกับ read operations.

นอกจากนี้ mongo นั้นยังมีคำสั่งบางอย่างเช่น findOneAndUpdate ที่ทำหน้าที่คล้ายกับ update ด้วย

อ่านเพิ่มเติม: Update Documents.

Delete Operations

Delete operations จะทำการลบ documents ออกจาก collection.

ใน MongoDB มี methods delete ดังต่อไปนี้

ใน MongoDB, delete operations จะมีผลกับ collection เดียวเท่านั้น. ทุกๆ delete operations ใน MongoDB ที่กระทำกับ single document จะเป็น atomic เสมอ.

ซึ่งเราสามารถใส่ filters เพื่อหา document ตามเงื่อนไขที่เราต้องการ โดยส่วนใหญ่จะใช้ syntax เดียวกันกับ read operations.

อ่านเพิ่มเติม: Delete Documents.

--

--

KhunGames
SkillLane

Software Engineer@skilllane ผู้ชื่นชอบ ประวัติศาสตร์ การเมือง สังคม และ ไอที