สร้าง Index แบบ Background เพื่อไม่บล็อคการทำงาน
บทความนี้สาธิตการสร้าง Index ใน MongoDB แบบ Background (พื้นหลัง) โดยใช้ตัวเลือก {background: true} ในคำสั่ง createIndex() ซึ่งทำให้การสร้าง Index ไม่ล็อก Collection และยังอ่าน/เขียนข้อมูลได้ปกติ
ไวยากรณ์ (Syntax)
db.yourCollectionName.createIndex(
{"yourFieldName1": 1, "yourFieldName2": 1},
{background: true}
);
ตัวอย่างการใช้งาน
> db.indexCreationDemo.createIndex({"StudentName":1,"StudentAge":1},{background: true});
{ "createdCollectionAutomatically": true, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 }
ตรวจสอบ Indexes ที่สร้าง
> db.indexCreationDemo.getIndexes();
ผลลัพธ์:
[
{ "v": 2, "key": { "_id": 1 }, "name": "_id_", "ns": "web.indexCreationDemo" },
{ "v": 2, "key": { "StudentName": 1, "StudentAge": 1 }, "name": "StudentName_1_StudentAge_1", "ns": "web.indexCreationDemo", "background": true }
]
สรุป:
background: trueทำให้การสร้าง Index ไม่บล็อค Operations อื่น (Non-blocking)- เหมาะสำหรับ Production Database ที่มี Traffic สูง
- Index จะปรากฏใน
getIndexes()พร้อมฟิลด์"background": true - หมายเหตุ: ตั้งแต่ MongoDB 4.2+ การสร้าง Index เป็น Background เป็นค่าเริ่มต้นแล้ว