การสร้างดัชนีรวมหลายฟิลด์เพื่อรองรับคำสั่ง OR
เมื่อต้องการสร้างดัชนีสำหรับหลายฟิลด์พร้อมกัน (Compound Index) ให้ใช้ createIndex() (แทน ensureIndex() ที่ล้าสมัย) โดยระบุลำดับฟิลด์และทิศทาง (1 = เรียงน้อยไปมาก, -1 = เรียงมากไปน้อย)
ตัวอย่างสร้างดัชนีหลายคู่
> db.demo53.createIndex({ "StudentFirstName": 1, "StudentAge": 1 });
> db.demo53.createIndex({ "StudentFirstName": 1, "StudentCountryName": 1 });
เพิ่มข้อมูลทดสอบ
> db.demo53.insertOne({ "StudentFirstName": "Chris", "StudentAge": 21, "StudentCountryName": "US" });
> db.demo53.insertOne({ "StudentFirstName": "David", "StudentAge": 23, "StudentCountryName": "UK" });
> db.demo53.insertOne({ "StudentFirstName": "Mike", "StudentAge": 24, "StudentCountryName": "AUS" });
แสดงข้อมูลทั้งหมด
> db.demo53.find();
ผลลัพธ์:
{ "_id": ObjectId("..."), "StudentFirstName": "Chris", "StudentAge": 21, "StudentCountryName": "US" }
{ "_id": ObjectId("..."), "StudentFirstName": "David", "StudentAge": 23, "StudentCountryName": "UK" }
{ "_id": ObjectId("..."), "StudentFirstName": "Mike", "StudentAge": 24, "StudentCountryName": "AUS" }
ข้อสังเกตสำคัญ
- ลำดับฟิลด์ในดัชนีสำคัญมาก: ดัชนี
{a:1, b:1}ช่วยคิวรีที่มี a อย่างเดียว หรือ a และ b ร่วมกัน แต่ไม่ช่วยคิวรีที่มี b อย่างเดียว - MongoDB ไม่มีดัชนี "OR" โดยตรง แต่ Compound Index ช่วยให้คิวรีที่มีเงื่อนไขหลายฟิลด์ทำงานได้เร็วขึ้น
- ใช้ createIndex() แทน ensureIndex() ซึ่งถูก deprecated แล้ว
สำหรับคำสั่งที่ใช้ $or ระหว่างฟิลด์ต่างกัน อาจพิจารณาสร้างดัชนีแยกสำหรับแต่ละฟิลด์ หรือใช้ Index Intersection ของ MongoDB