MongoDB เป็นฐานข้อมูลแบบ Schema-less (ไม่มีโครงสร้างคงที่) จึงไม่มีแนวคิดของ "ตาราง" (Table) หรือ "คอลัมน์" (Column) เหมือนฐานข้อมูลเชิงสัมพันธ์ (Relational Database) แทนที่จะเป็น MongoDB ใช้แนวคิดของ คอลเลกชัน (Collection) และ เอกสาร (Document)
ความแตกต่างหลัก
- Collection = คล้ายกับ Table แต่ไม่บังคับโครงสร้าง
- Document = คล้ายกับ Row/A Record แต่เก็บข้อมูลในรูปแบบ BSON (Binary JSON)
- Field = คล้ายกับ Column แต่แต่ละ Document สามารถมี Field ที่ต่างกันได้
คำสั่งพื้นฐาน
// เพิ่มเอกสาร (Field สามารถต่างกันได้ในแต่ละ Document)
db.yourCollectionName.insertOne({"fieldName1": value1, "fieldName2": "value2", ...});
// ดึงเอกสารเดียว
db.yourCollectionName.findOne();
// ดึงเอกสารทั้งหมด
db.yourCollectionName.find();
ตัวอย่าง: เอกสารในคอลเลกชันเดียวกันมีฟิลด์ต่างกัน
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"Larry"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c953b98749816a0ce933682") }
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"David","UserAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5c953ba4749816a0ce933683") }
> db.collectionOnDifferentDocumentDemo.insertOne({"UserName":"Carol","UserAge":25,"UserCountryName":"US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5c953bb8749816a0ce933684") }
แสดงผลด้วย find():
{ "_id" : ObjectId("5c953b98749816a0ce933682"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c953ba4749816a0ce933683"), "UserName" : "David", "UserAge" : 24 }
{ "_id" : ObjectId("5c953bb8749816a0ce933684"), "UserName" : "Carol", "UserAge" : 25, "UserCountryName" : "US" }
แสดงผลด้วย findOne() (เอกสารแรก):
{ "_id" : ObjectId("5c953b98749816a0ce933682"), "UserName" : "Larry" }
สรุป
ความยืดหยุ่นของ MongoDB อยู่ที่แต่ละ Document ใน Collection เดียวกันสามารถมีโครงสร้าง Field ต่างกันได้ ทำให้เหมาะกับข้อมูลที่ไม่มีโครงสร้างคงที่หรือเปลี่ยนแปลงบ่อย