title: Opening and closing 16000 Mongo DB instances in PHP
body: <p>I am currently working on some personal tests and benchmarks to compare the workflow and efficiency between using MongoDB and MySQL with real world example data.</p>
  
  <p>To setup my data in each database I am doing several thousand loops and randomly creating data objects to insert into the database.</p>
  
  <p>However I am having some issues using the Mongo class in PHP which I cannot solve. The problem is like so:</p>
  
  <p>I have a loop which creates a new Mongo instance and connection, inserts a small array into a collection and then closes the connection. This loop should run 20000 times. However it is always failing around the 16300nd loop (with a min of 16200 and max of 16350 I'd say after a few runs) when it attempts to create the instance/make a connection.</p>
  
  <p>The code in the loop is below:</p>
  
  <pre><code>$data = get_random_user_data();
  
  $mongo = new Mongo('mongodb://admin:password@localhost:27017/test');
  
      if ($mongo-&gt;test-&gt;users-&gt;insert($data)) {
          $users[] = array('id' =&gt; $data['_id'], 'name' =&gt; $data['username']);
      echo $i." - Added user: ".$data['username'].'&lt;br/&gt;';
      }
  
  $mongo-&gt;close();
  </code></pre>
  
  <p>get_random_user_data() just returns a simple associative array.</p>
  
  <p>The error I get is:</p>
  
  <pre><code>Fatal error: Uncaught exception 'MongoConnectionException' with message 'Unknown error'
  </code></pre>
  
  <p>On the line: </p>
  
  <pre><code>$mongo = new Mongo('mongodb://admin:password@localhost:27017/test');
  </code></pre>
  
  <p>Any ideas? Is there something fundamental I am missing like some security or spam-prevention?</p>
  
  <p>Thanks in advance.</p>
  
  <p><strong>Extra info:</strong></p>
  
  <p>The script dies at about 114.9797 seconds. It's not a PHP memory or time based issue as all the limits are raised and I ran my MySQL benchmarks yesterday inserting 120000 rows (with the same method of looping open connection, insert, close connection) over about an hour with no problems.</p>
  
  <p>Running PHP Version 5.3.5</p>
  
  <p><strong>phpinfo Mongo info:</strong></p>
  
  <pre><code>MongoDB Support enabled
  Version 1.2.0-
  Directive   Local Value Master Value
  mongo.allow_empty_keys  0   0
  mongo.allow_persistent  1   1
  mongo.auto_reconnect    1   1
  mongo.chunk_size    262144  262144
  mongo.cmd   $   $
  mongo.default_host  localhost   localhost
  mongo.default_port  27017   27017
  mongo.long_as_object    0   0
  mongo.native_long   0   0
  mongo.no_id 0   0
  mongo.utf8  1   1
  </code></pre>