การสร้างดัชนีร่วม (Compound Index) ที่รวมฟิลด์ธรรมดาและฟิลด์ในอาร์เรย์ (Multikey Index) ใช้ createIndex() (แทน ensureIndex ที่ deprecated)
> db.demo678.createIndex({id: 1, "details.userId": 1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
Insert ข้อมูลทดสอบ:
> db.demo678.insertOne({
... id: 101,
... "details": [
... {"userId": "1001", "userName": "Chris"},
... {"userId": "1002", "userName": "David"}
... ],
... "otherDetails": [
... {CountryName: "US", EmailId: ["Chris@gmail.com", "David@gmail.com"]}
... ]
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5ea4276904263e90dac943fc") }
แสดงข้อมูล:
> db.demo678.find();
Compound Multikey Index
Index
{id: 1, "details.userId": 1}เป็น:
- Compound: รวม 2 ฟิลด์ (id + details.userId)
- Multikey: details.userId เป็นอาร์เรย์ → MongoDB สร้าง index entry สำหรับแต่ละค่าในอาร์เรย์
คิวรีที่ใช้ Index นี้ได้
// ใช้ index ได้ทั้งคู่
db.demo678.find({id: 101, "details.userId": "1001"});
// ใช้ index ได้บางส่วน (prefix)
db.demo678.find({id: 101});
// ไม่ใช้ index นี้ (ไม่มี id prefix)
db.demo678.find({"details.userId": "1001"});
ข้อจำกัด Multikey Index
- คอลเลกชันมีได้ Multikey Index เพียง 1 ตัวต่อคอลเลกชัน (สำหรับ compound multikey)
- ไม่สามารถสร้าง Compound Index ที่มี 2 ฟิลด์อาร์เรย์ พร้อมกันได้ (เช่น {"details.userId": 1, "otherDetails.EmailId": 1} ❌)
- Unique constraint บน Multikey index: unique ต่อเอกสาร ไม่ใช่ต่อค่าในอาร์เรย์
ตรวจสอบ Index
db.demo678.getIndexes();
ดู "multikey": true ในผลลัพธ์