当我第一次从PHP连接到MongoDB时出错 - 当我刷新页面时就消失了

So I have a PHP script that connects to Mongo using the regular connection method:

$this->mongo = new MongoClient( "mongodb://<connection param>" );
$this->mongoSynthCollection = $this->mongo->map->Synth;
$cursor = $this->mongoSynthCollection ->find();

I then proceed to parse and work with the synthCollection object. When I load this file for the first time (by first time I mean say, in the morning for example) I get an error:

Fatal error: Uncaught exception 'MongoCursorException' with message 'WSA error getting database response Read timed out after reading 0 bytes, waited for 30.000000 seconds'

If I refresh the page, then the error goes away, I get the collection object and I can work with it without any problems. If I leave the page idle for a while, and then try again then the problem returns.

Note: I am not using any session whatsoever in the page, as my app logic does not require sessions. I also have set_time_limit(0) set in my PHP script, not that I think that it matters in this case anyway.

I am not sure what is wrong here, I would appreciate any pointers.

In my experience, this is/was normal after a server restart for the first connection to Mongo. It has to do with persistent connections and the server dropping them. See here: https://jira.mongodb.org/browse/PHP-636

That being said, the error you're getting is because you're not double-checking your connection before you run the query. If you did something like this:

try{
    $this->mongo = new MongoClient();
}catch(MongoConnectionException $e){
    var_dump($e);
}

You would likely end up with:

["message":protected]=>
string(78) "Failed to connect to: localhost:27017: Remote server has closed the connection"
["string":"Exception":private]=>
string(0) ""
["code":protected]=>
int(71)