Để kiểm tra index hoạt động đúng với $elemMatch, sử dụng phương thức explain() để phân tích query plan.
Tạo sparse index trên trường lồng nhau và thêm dữ liệu:
> 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") }
Hiển thị dữ liệu:
> db.workingOfIndexesDemo.find();
{ "_id" : ObjectId("5e06f94825ddae1f53b621f7"), "Information" : { "StudentDetails" : { "StudentName" : "Chris" } } }
{ "_id" : ObjectId("5e06f94f25ddae1f53b621f8"), "Information" : { "StudentDetails" : { "StudentName" : "David" } } }
{ "_id" : ObjectId("5e06f95325ddae1f53b621f9"), "Information" : { "StudentDetails" : { "StudentName" : "Mike" } } }
Chạy truy vấn $elemMatch với explain() để xem query plan:
> db.workingOfIndexesDemo.find({"Information.StudentDetails": { $elemMatch: { "StudentName" : "David"} } }).explain();
Kết quả explain cho thấy winningPlan sử dụng IXSCAN (index scan) trên index "Information.StudentDetails.StudentName_1", xác nhận index đang hoạt động:
{
"queryPlanner" : {
"winningPlan" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : { "Information.StudentDetails.StudentName" : 1 },
"indexName" : "Information.StudentDetails.StudentName_1",
"isSparse" : true,
...
}
}
},
"ok" : 1
}