如果我的查询包含 $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 }
广告