How to set timeout to infinite to avoid MongoCursorTimeoutException in php
Asked Answered
H

4

12

I am running the php script which fetch data from mongodb. I have a very huge database and I am getting this exception ..my mongodb version is 1.6.5

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

My query is like this

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']);
  }

how can I set timeout to infinite so that i do nt get this exception

Heptagonal answered 6/4, 2011 at 5:37 Comment(0)
H
21

MongoCursor::$timeout = -1;

type above line in your php code. this set timeout for all queries . best regard,

Hemispheroid answered 1/10, 2013 at 7:42 Comment(3)
Or you can do MongoCursor::$timeout = $yourTimeInMS to set any timeout you want before the query.Tiphani
Note this is deprecated in >= 1.5Gilud
This was a good solution, unfortunately cannot be used with the latest php mongo driver, actually causing script to exit (depending on your error level setting)Ethanethane
G
12

Here's documentation for setting the timeout on a cursor.

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

The command method does not return a cursor it returns an array.

If you take a look at the documentation for the command method, you'll see that it's actually just a wrapper for the following:

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

That should get you going in the right direction.

Gutow answered 6/4, 2011 at 6:50 Comment(1)
Or just: MongoCursor::$timeout = -1;Glacis
P
5

The PHP driver supports a second argument in the command method to set the timeout.

This means you should do the following:

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

This should solve your problem!

Pilloff answered 13/11, 2013 at 18:23 Comment(0)
P
2

I think, by the first step you should check how mongodb works with your query

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

And, if needs add indexes to specified fields by

db.collection.ensureIndex(...)

And only than if your query is optimal, set timeout: -1

Predicable answered 4/6, 2013 at 7:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.