ลดเวลาค้นหาใน MongoDB ด้วยการสร้าง Index
บทความนี้สาธิตวิธีแก้ไขปัญหาการค้นหาช้า (Slow Query) ใน MongoDB โดยการสร้าง Index (ดัชนี) บนฟิลด์ที่ใช้ค้นหาบ่อย โดยใช้ createIndex()
ขั้นตอนที่ 1: สร้าง Collection และสร้าง Index พร้อมกัน
สร้าง collection ชื่อ decreasetimeusingindex และสร้าง Index บน StudentName แบบ Ascending (1) ก่อน Insert ข้อมูล
> db.decreasetimeusingindex.createIndex({"StudentName": 1});
{ "createdCollectionAutomatically": true, "numIndexesBefore": 1, "numIndexesAfter": 2, "ok": 1 }
> db.decreasetimeusingindex.insertOne({"StudentName":"John Smith","StudentAge":21});
{ "acknowledged": true, "insertedId": ObjectId("5e03960af5e889d7a51994ff") }
> db.decreasetimeusingindex.insertOne({"StudentName":"John Doe","StudentAge":24});
{ "acknowledged": true, "insertedId": ObjectId("5e039611f5e889d7a5199500") }
> db.decreasetimeusingindex.insertOne({"StudentName":"Adam Smith","StudentAge":22});
{ "acknowledged": true, "insertedId": ObjectId("5e03961df5e889d7a5199501") }
ขั้นตอนที่ 2: แสดงข้อมูลทั้งหมด
> db.decreasetimeusingindex.find().pretty();
ขั้นตอนที่ 3: ค้นหาเอกสารเฉพาะ (จะใช้ Index)
> db.decreasetimeusingindex.find({"StudentName":"Adam Smith"});
ผลลัพธ์:
{ "_id": ObjectId("5e03961df5e889d7a5199501"), "StudentName": "Adam Smith", "StudentAge": 22 }
สรุป:
- การสร้าง Index บนฟิลด์ที่ใช้ใน Query บ่อย (
StudentName) จะทำให้ MongoDB ใช้ Index Scan (IXSCAN) แทน Collection Scan (COLLSCAN) - Index ควรสร้างก่อน Insert ข้อมูลมากๆ เพื่อประสิทธิภาพ
- ตรวจสอบ Query Plan ด้วย
explain()เพื่อยืนยันว่าใช้ Index จริง