ดัชนี (Index) ช่วยให้การ query เร็วขึ้น ใช้ createIndex() (เวอร์ชันใหม่) หรือ ensureIndex() (เวอร์ชันเก่า/ยังรองรับ)
รูปแบบคำสั่ง
// เวอร์ชันใหม่ (แนะนำ)
db.collection.createIndex({ "fieldName": 1 }, { unique: true });
// เวอร์ชันเก่า (ยังทำงานได้)
db.collection.ensureIndex({ "fieldName": 1 }, { unique: true });
1= Ascending (น้อยไปมาก)-1= Descending (มากไปน้อย){ unique: true }= บังคับค่าไม่ซ้ำ (Unique Index)
ตัวอย่าง: สร้าง Unique Index บน UserCountryName
1. สร้างคอลเลกชัน
> db.createCollection("creatingUniqueIndexDemo");
2. สร้าง Unique Index
> db.creatingUniqueIndexDemo.ensureIndex({ "UserCountryName": 1 }, { unique: true });
{ "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
3. Insert ข้อมูลทดสอบ
> db.creatingUniqueIndexDemo.insertOne({"UserName":"John","UserAge":21,"UserCountryName":"US"});
> db.creatingUniqueIndexDemo.insertOne({"UserName":"Mike","UserAge":23,"UserCountryName":"UK"});
> db.creatingUniqueIndexDemo.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"US"});
// Error: E11000 duplicate key error ... UserCountryName_1 dup key: { : "US" }
> db.creatingUniqueIndexDemo.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"AUS"});
4. ผลลัพธ์: US ถูกบล็อกครั้งที่ 2, AUS ผ่าน
> db.creatingUniqueIndexDemo.find().pretty();
{ "_id" : ..., "UserName" : "John", "UserAge" : 21, "UserCountryName" : "US" }
{ "_id" : ..., "UserName" : "Mike", "UserAge" : 23, "UserCountryName" : "UK" }
{ "_id" : ..., "UserName" : "Robert", "UserAge" : 26, "UserCountryName" : "AUS" }
ประเภท Index ที่สำคัญ
| ประเภท | คำสั่ง | ใช้เมื่อไหร่ |
|---|---|---|
| Single Field | { field: 1 } | Query บนฟิลด์เดียวบ่อย |
| Compound | { field1: 1, field2: -1 } | Query หลายฟิลด์พร้อมกัน |
| Unique | { field: 1 }, { unique: true } | บังคับค่าไม่ซ้ำ (เช่น email) |
| Text | { field: "text" } | Full-text search |
| TTL | { field: 1 }, { expireAfterSeconds: 3600 } | Auto-delete ข้อมูลเก่า |
คำสั่งจัดการ Index
db.collection.getIndexes(); // ดู index ทั้งหมด
db.collection.dropIndex("indexName"); // ลบ index
db.collection.dropIndexes(); // ลบ index ทั้งหมด (ยกเว้น _id)
สรุป
- ใช้
createIndex()สำหรับโค้ดใหม่ - Unique Index ป้องกันข้อมูลซ้ำได้ที่ระดับ Database
- Compound index เรียงลำดับฟิลด์สำคัญ (Equality → Sort → Range)
- Index ใช้หน่วยความจำและช้าการเขียนเล็กน้อย ใช้จำเป็นเท่านั้น