2011-04-06 82 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) 
); 

这应该解决您的问题!