我在mongodb collection / table中插入了记录。如果我传递像StoreId = 1
这样的集合中可用的数据,一切正常问题:如果我搜索像StoreId = 3这样的集合中没有的数据,则需要花费太长时间才能回复原因????我该如何简化这个问题?
插入数据:
$data = array();
$data[] = array("StoreId" => "1","StoreName" => "abc");
$data[] = array("StoreId" => "2","StoreName" => "xyz");
$db->test->insertMany($data);
获取记录:
$arrFind = array(
'$and' => array(
array(
'StoreId' => "1"
),
array(
'StoreName' => array(
'$regex' => '^ab',
'$options' => 'i'
)
)
)
);
$projection = array("_id" => false);
$result = $db->test->find($arrFind,['limit'=>$data['Count'], 'projection' => $projection ]);
$array1 = iterator_to_array($result, false);
echo "<pre>";
print_r($array1);
上面的示例工作查找非常快速地返回输出,但是如果我通过StoreId = 3则响应空白输出花费的时间太长。
Mongodb:
db.test.find( { StoreId: "1" } ).pretty() //returns output quickly
db.test.find( { StoreId: "3" } ).pretty() //taking too-long time for blank output.
解释
db.test.find( { StoreId: "3" } ).explain(true)
{
"queryPlanner" : {
"plannerVersion" : 1,
"namespace" : "mydb.test",
"indexFilterSet" : false,
"parsedQuery" : {
"StoreId" : {
"$eq" : "3"
}
},
"winningPlan" : {
"stage" : "COLLSCAN",
"filter" : {
"StoreId" : {
"$eq" : "3"
}
},
"direction" : "forward"
},
"rejectedPlans" : [ ]
},
"executionStats" : {
"executionSuccess" : true,
"nReturned" : 0,
"executionTimeMillis" : 35083,
"totalKeysExamined" : 0,
"totalDocsExamined" : 6816823,
"executionStages" : {
"stage" : "COLLSCAN",
"filter" : {
"StoreId" : {
"$eq" : "3"
}
},
"nReturned" : 0,
"executionTimeMillisEstimate" : 34087,
"works" : 6816825,
"advanced" : 0,
"needTime" : 6816824,
"needYield" : 0,
"saveState" : 53988,
"restoreState" : 53988,
"isEOF" : 1,
"invalidates" : 0,
"direction" : "forward",
"docsExamined" : 6816823
},
"allPlansExecution" : [ ]
},
"serverInfo" : {
"host" : "Neha-PC",
"port" : 27017,
"version" : "3.6.3",
"gitVersion" : "9586e557d54ef70f9ca4b43c26892cd55257e1a5"
},
"ok" : 1
}
答案 0 :(得分:2)
你需要在&#34; StoreId&#34;上创建索引。减少了查找
您可以使用以下命令
检查为集合创建的所有索引的内容db.test.getIndexKeys();
要创建索引,您可以使用以下命令
db.test.createIndex( { StoreId: 1 } );
在您的集合上创建索引后尝试运行查询,它应该是快速的
了解更多信息 https://docs.mongodb.com/manual/reference/method/db.collection.createIndex/
答案 1 :(得分:1)
因为您没有可用于此查询的任何索引,所以MongoDB需要检查集合中的每个文档。大集合上的集合扫描(&#34; COLLSCAN&#34;)非常慢。您需要从StoreId
元素创建索引。