MongoDB เบื้องต้น version 4.2
มาทำความรู้จัก mongoDB กันนะครับ!!
mongoDB คืออะไร?
คือ database ในอีกรูปแบบ โดยจัดเก็บข้อมูลเป็น Document store model รูปแบบคล้ายๆ JSON ที่จะมี field และ value ที่เรียกว่า BSON ซื้งจะทำให้ง่ายต่อการ update structured นั้นเอง
ก่อนอื่น ติดตั้ง install MongoDB หรือ ใช้ MongoDB Atlas Free Tier Cluster
Key word
- documents: คือ BSON ข้อมูลที่บันทึก
- collection คือ กลุ่มของ documents (BSON) ที่อยู่ในเรื่องเดียวกัน คล้าย table ในกลุ่ม relational
Insert Documents
จะเพื่อ documents ใน collection ชื่อ inventory พร้อมกันหลาย documents โดยใช้ db.collection.insertMany()
db.inventory.insertMany([
// ใน MongoDB ถ้าไม่ใส่ _id จะ บันทึกเป็น ObjectId
{ _id: 1, item: "journal", qty: 25, status: "A",
size: { h: 14, w: 21, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "notebook", qty: 50, status: "A",
size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank" ] },
{ item: "paper", qty: 100, status: "D",
size: { h: 8.5, w: 11, uom: "in" }, tags: [ "red", "blank", "plain" ] },
{ item: "planner", qty: 75, status: "D",
size: { h: 22.85, w: 30, uom: "cm" }, tags: [ "blank", "red" ] },
{ item: "postcard", qty: 45, status: "A",
size: { h: 10, w: 15.25, uom: "cm" }, tags: [ "blue" ] }
]);
insertMany()
จะ return เป็น _id ที่ได้ บันทึก
ถ้าต้องการเพิ่ม document ที่ละตัว ใช้ db.collection.insertOne()
นะครับ
Query Documents
ค้นหา Documents
สามารถใช้ db.collection.find()
ในการค้นหารายตัว หรือ ทั้งหมดก็ได้ โดยถ้าค้นหาทั้งหมด เราก็ส่ง query ว่างไป
db.inventory.find()
เเล้วถ้าต้องการ ระบุ รายละเอียดขอ document ที่ต้องการหา ก็ระบุลงไปใน query เช่น ให้ค้นหา status เท่ากับ D และ qty มากกว่า 75
db.inventory.find( { status: "D", qty: {$gt: 75} } )
แล้วถ้าต้องการระบุรายละเอียด ลึกลงไปใน field อีก ก็สามารถระบุที่ field ของ query ด้วย ‘.’ ตาม structure ของ document ได้เลยครับ เช่น ต้องการ document ที่size ต้อง h น้อยกว่า 15 และ w มากกว่า 20
db.inventory.find( { "size.h": {$lt: 15}, "size.w": {$gt: 20}} )
แล้วถ้าจะค้นหา document ที่เป็น array ก็สามารถทำได้ระบุลงไปใน query ได้เลยครับ เช่น ต้องการหา tags ที่มี red ใน array
db.inventory.find( { tags: "red" } )
ข้อสังเกต ถ้า ระบุ tags: [“red”, “blank”]
ก็จะเท่ากับว่าให้หา document ที่ tags มี value เท่ากับ [“red”, “blank”]
เท่านั้น!!
db.createCollection()
ไว้สร้าง Collection create
.
db.getCollectionInfos()
ไว้ดู collection ของ Database ที่เราใช้อยู่ ปัจจุบัน use myDB
อ้างอิง