2011-04-06 44 views
11

我正在運行從mongodb獲取數據的php腳本。我有一個非常龐大的數據庫,我得到這個例外..my MongoDB的版本是1.6.5如何將超時設置爲無限以避免MongoCursorTimeoutException在php

PHP Fatal error: Uncaught exception 'MongoCursorTimeoutException' 
with message 'cursor timed out 
(timeout: 30000, time left: 0:0, status: 0) 

我的查詢是這樣的

private function executeRegex($start_date, $end_date, $source, $collection, $db) 
    { 
    $criteria = array(
     'date' => array(
      '$gte' => new MongoDate(strtotime($start_date)), 
      '$lt' => new MongoDate(strtotime($end_date)) 
     ), 
     'uid'=> array(
      '$ne' => '-', 
     ), 
     'source' => new MongoRegex($source) 
     ); 
    $value = $db->command(array('distinct' => $collection, 'key' => 'uid', 'query' => $criteria)); 
    return count($value['values']); 
    } 

我怎麼可以設置超時爲無窮,這樣我不會得到此異常

回答

12

下面是設置timeout on a cursor的文檔。

$cursor = $collection->find()->timeout(n); 

command方法不返回遊標它返回一個數組。

如果你看一看的command method的文件,你會看到,它實際上只是一個包裝以下:

public function command($data) { 
    return $this->selectCollection('$cmd')->findOne($data); 
} 

這應該讓你在正確的方向前進。

+9

或者只是:MongoCursor :: $ timeout = -1; – user956584 2012-07-24 15:07:44

2

我認爲,在第一步驟中,你應該檢查MongoDB中如何與您的查詢

db.collection.find(...).explain() 

而且,如果需要通過

db.collection.ensureIndex(...) 

添加索引到指定字段,只比如果您的查詢是最優的,設置超時時間:-1

20

MongoCursor :: $ timeout = -1;

在您的php代碼中鍵入上面的行。這個設置超時的所有查詢。 最好的方面,

+0

或者您可以在執行查詢前設置'MongoCursor :: $ timeout = $ yourTimeInMS'來設置任何超時。 – Marcin 2013-10-18 08:53:00

+5

請注意,這是廢棄在> = 1.5 – farzan 2014-05-18 14:22:17

+0

這是一個很好的解決方案,不幸的是不能用於最新的PHP mongo驅動程序,實際上導致腳本退出(取決於您的錯誤級別設置) – Dmitri 2014-11-04 14:53:07

5

PHP驅動程序支持命令方法中設置超時的第二個參數。

這意味着你應該做到以下幾點:

$value = $db->command(
    array('distinct' => $collection, 'key' => 'uid', 'query' => $criteria), 
    array('timeout' => 10000000000) 
); 

這應該解決您的問題!