执行$ elemMatch时,MongoDB索引不起作用?
要使用$elemMatch正确实现索引,您需要使用的概念explain()。首先让我们创建一个包含文档的集合-
> 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")
}以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.workingOfIndexesDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5e06f94825ddae1f53b621f7"), "Information" : { "StudentDetails" : { "StudentName" : "Chris" } } }
{ "_id" : ObjectId("5e06f94f25ddae1f53b621f8"), "Information" : { "StudentDetails" : { "StudentName" : "David" } } }
{ "_id" : ObjectId("5e06f95325ddae1f53b621f9"), "Information" : { "StudentDetails" : { "StudentName" : "Mike" } } }以下是explain()在MongoDB中执行$elemMatch的查询-
> db.workingOfIndexesDemo.find({"Information.StudentDetails": { $elemMatch: { "StudentName" : "David"} } } ).explain();这将产生以下输出-
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.workingOfIndexesDemo",
"indexFilterSet" : false,
"parsedQuery" : {
"Information.StudentDetails" : {
"$elemMatch" : {
"StudentName" : {
"$eq" : "David"
}
}
}
},
"winningPlan" : {
"stage" : "FETCH",
"filter" : {
"Information.StudentDetails" : {
"$elemMatch" : {
"StudentName" : {
"$eq" : "David"
}
}
}
},
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"Information.StudentDetails.StudentName" : 1
},
"indexName" : "Information.StudentDetails.StudentName_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"Information.StudentDetails.StudentName" : [ ]
},
"isUnique" : false,
"isSparse" : true,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"Information.StudentDetails.StudentName" : [
"[\"David\", \"David\"]"
]
}
}
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "DESKTOP-QN2RB3H",
"port" : 27017,
"version" : "4.0.5",
"gitVersion" : "3739429dd92b92d1b0ab120911a23d50bf03c412"
},
"ok" : 1
}