MongoDB x Docker Start to Max
MongoDB คืออิหยั่งนะ ?…
MongoDB เป็น open-source document database เป็นฐานข้อมูลแบบ NoSQL คือไม่มี relation แบบ SQL ทั่วๆไป เก็บข้อมูลเป็นแบบ JSON การบันทึกข้อมูลทุกๆ record จะเรียกมันว่า Document ซึ่งจะเก็บค่าเป็น key และ value
ติดตั้ง MongoDB ใน Docker
Step 1: Install and Run container ขึ้นมาจาก image และทำการ map volume เพื่อเก็บ data ของ MongoDB ไว้ข้างนอก container ที่ path ~/mongodb-docker
docker run -d -p 2717:27017 -v ~/mongodb-docker:/data/db --name mymongo mongo:latest
ตรวจสอบการ install mongoDB
docker images
ตรวจสอบการ run container
docker ps
Step 3 : เข้าไป console container
docker exec -it mymongo bash
Step 4 : รันเพื่อเข้า mongo shell
mongo
Step 5 : คำสั่ง show database ที่เริ่มต้นของ mongo
show dbs
Step 6 : ทำการสร้างและเรียกใช้งาน database
> use animalswitched to db animal
Step 7 : สร้าง Collection
> db.createCollection('amphibians'){ "ok" : 1 }
Step 8 : Show collection
> show collectionsamphibians
Note * ลบ Collection
db.getCollection("amphibians").drop();
- Insert data collection
> db.amphibians.insert({"name":"bullfrog"})WriteResult({ "nInserted" : 1 })
2. Find เพื่อดูข้อมูล
> db.amphibians.find(){ "_id" : ObjectId("608196e4a4082bfb6ad70c3c"), "name" : "bullfrog" }
ค้นหาแสดงอย่างมีรูปแบบ pretty()
> db.amphibians.find().pretty()
{ "_id" : ObjectId("608196e4a4082bfb6ad70c3c"), "name" : "bullfrog" }{ "_id" : ObjectId("608197c6a4082bfb6ad70c3d"), "name" : "frog" }{"_id" : ObjectId("608198e9a4082bfb6ad70c3f"),"name" : "test","lname" : "yama"}
ค้นหาข้อมูลแบบมี limit ex. limit(2) แสดงจำนวน 2 record
> db.amphibians.find().limit(2)
3. insert ข้อมูลที่เป็น array ได้ด้วยเด้อ…
> db.amphibians.insert(
[
{"name":"frog"},
{"name":"toad"}
])
4. ค้นหาข้อมูลแบบมีเงื่อนไข Where name = “frog”
> db.amphibians.find({ name: "frog" });{ "_id" : ObjectId("608197c6a4082bfb6ad70c3d"), "name" : "frog" }
5. Update ข้อมูล set lname = “yama” Where name = “test”
db.amphibians.update({name:"test"},{$set:{ lname : "yama"} })
6. Delete ข้อมูลแบบมีเงื่อนไข Where name = “toad”
db.amphibians.remove({ name: "toad" })
เป็นอย่างไรกันบ้างครับ หวังว่าจะมีประโยขน์กับคนที่สนใจ ลองใช้งาน MongoDB กันนะครับ สุดท้ายนี้ Good Luck to you…. เด้อ..