เพื่อให้ดัชนีทำงานถูกต้องกับ $elemMatch ต้องใช้ explain() เพื่อตรวจสอบแผนการค้นหา (Query Plan)
สร้างคอลเลกชัน สร้างดัชนีแบบ Sparse และ Background บนฟิลด์ Information.StudentDetails.StudentName แล้วเพิ่มเอกสาร:
> db.workingOfIndexesDemo.createIndex({"Information.StudentDetails.StudentName":1},{ sparse : true, background : true } );
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.workingOfIndexesDemo.insertOne({"Information":{"StudentDetails":{"StudentName":"Chris"}}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f94825ddae1f53b621f7") }
> db.workingOfIndexesDemo.insertOne({"Information":{"StudentDetails":{"StudentName":"David"}}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f94f25ddae1f53b621f8") }
> db.workingOfIndexesDemo.insertOne({"Information":{"StudentDetails":{"StudentName":"Mike"}}});
{ "acknowledged" : true, "insertedId" : ObjectId("5e06f95325ddae1f53b621f9") }
แสดงเอกสารทั้งหมด:
> db.workingOfIndexesDemo.find();
ผลลัพธ์ - 3 เอกสาร มี StudentName คือ Chris, David, Mike:
คำสั่งใช้ $elemMatch ค้นหา StudentName = "David" พร้อม
explain()เพื่อดูแผนการค้นหา:> db.workingOfIndexesDemo.find({"Information.StudentDetails": { $elemMatch: { "StudentName" : "David"} } } ).explain();ผลลัพธ์ explain() แสดงว่าใช้ IXSCAN (Index Scan) บนดัชนี "Information.StudentDetails.StudentName_1" แสดงว่าดัชนีทำงานถูกต้อง: