如果查询中包含$ or运算符,是否可以查询MongoDB索引?
是的,你可以这么做。首先,您需要创建一个索引,然后使用explain()。让我们首先创建一个MongoDB索引。以下是查询:
> db.indexOrQueryDemo.ensureIndex({"First":1});这将产生以下输出
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 2,
"numIndexesAfter" : 3,
"ok" : 1
}创建第二个索引的查询如下
> db.indexOrQueryDemo.ensureIndex({"Second":1});这将产生以下输出
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 3,
"numIndexesAfter" : 4,
"ok" : 1
}以下是对带有索引的$or运算符的查询。我们explain()在这里也使用过
> db.indexOrQueryDemo.find({$or:[{First:1}, {Second:2}]}).explain();这将产生以下输出
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "test.indexOrQueryDemo",
"indexFilterSet" : false,
"parsedQuery" : {
"$or" : [
{
"First" : {
"$eq" : 1
}
},
{
"Second" : {
"$eq" : 2
}
}
]
},
"winningPlan" : {
"stage" : "SUBPLAN",
"inputStage" : {
"stage" : "FETCH",
"inputStage" : {
"stage" : "OR",
"inputStages" : [
{
"stage" : "IXSCAN",
"keyPattern" : {
"First" : 1
},
"indexName" : "First_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"First" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"First" : [
"[1.0, 1.0]"
]
}
},
{
"stage" : "IXSCAN",
"keyPattern" : {
"Second" : 1
},
"indexName" : "Second_1",
"isMultiKey" : false,
"multiKeyPaths" : {
"Second" : [ ]
},
"isUnique" : false,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"Second" : [
"[2.0, 2.0]"
]
}
}
]
}
}
},
"rejectedPlans" : [ ]
},
"serverInfo" : {
"host" : "DESKTOP-QN2RB3H",
"port" : 27017,
"version" : "4.0.5",
"gitVersion" : "3739429dd92b92d1b0ab120911a23d50bf03c412"
},
"ok" : 1
}