执行 $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
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP