Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MongoDb driver: How to set timeout for executing a code

Tags:

php

mongodb

I have the following code which executes a piece of code on the MongoDb's side:

$mongoCode = new MongoCode('/* Some JS code */');
$db->execute($mongoCode, array(
    'socketTimeoutMS' => 1000000,
));

As you see I have tried to set timeout for the code's execution by setting the socketTimeoutMS value in second parameter of execute() function. But it does not work. Documentations in PHP website indicate that the second parameter of execute() command is sent to code as arguments. How can I set timeout for MongoDB::execute()? Please note that I am using version 1.5 of MongoDB driver for php and MongoCursor::$timeout is deprecated and does not work anymore.

like image 579
farzan Avatar asked Mar 20 '23 06:03

farzan


1 Answers

You can set the socketTimeoutMS on MongoClient:

$mongo = new MongoClient("mongodb://localhost:27017", 
    array(
        "socketTimeoutMS" => 100000
    )
); 

The args parameters for the execute method are passed to the code not to the driver.

You can also set a timeout just when executing the command:

$result = $mongo->dbname->command(
    ['eval' => $code],
    ['socketTimeoutMS' => 1]
);

Alternatively, if you're not executing commands, you can set the timeout on the cursor:

$cursor = $collection->find([]);
$cursor->timeout(10000);

This will obviously not work on the execute command, because that command doesn't return a cursor.

like image 115
Christian P Avatar answered Mar 22 '23 16:03

Christian P