การอธิบาย Query Plan ด้วย explain()
สำหรับข้อมูล Query Plan ให้ใช้ explain() ใน MongoDB
สร้าง Collection พร้อม Index และข้อมูล
> db.demo637.ensureIndex({ClientName:1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo637.insert({ClientName:"John"});
WriteResult({ "nInserted" : 1 })
> db.demo637.insert({ClientName:"Bob"});
WriteResult({ "nInserted" : 1 })
> db.demo637.insert({ClientName:"Johnson"});
WriteResult({ "nInserted" : 1 })
แสดงเอกสารทั้งหมด
> db.demo637.find();
ผลลัพธ์:
{ "_id" : ObjectId("5e9c26916c954c74be91e6db"), "ClientName" : "John" }
{ "_id" : ObjectId("5e9c26936c954c74be91e6dc"), "ClientName" : "Bob" }
{ "_id" : ObjectId("5e9c269d6c954c74be91e6dd"), "ClientName" : "Johnson" }
Case 1: Regexp /john/ (ไม่ได้ใช้ Index อย่างมีประสิทธิภาพ)
> db.demo637.find({ClientName:/john/}).explain();
ผลลัพธ์ Query Planner แสดงว่าใช้ IXSCAN แต่มี Filter สำหรับ Regex
Case 2: Regexp /^john/ (ใช้ Index ได้อย่างมีประสิทธิภาพ)
> db.demo637.find({ClientName:/^john/}).explain();
ผลลัพธ์ Query Planner แสดงว่า IXSCAN มี Index Bounds ที่ชัดเจนสำหรับ Prefix "john"