title: PHP MongoDB findOne Memory Leak
body: <p>I have found some old posts regarding the problem of a memory leak with the php mongodb driver. But none gave a final solution or explenation for older versions of the php mongodb driver.</p>
  
  <p>My Version of the Driver is 1.4.5 (stable)
  with PHP 5.3.10</p>
  
  <p><strong>Code with Debug echos:</strong></p>
  
  <pre><code>     echo memory_get_usage()." in MB : "; 
          echo memory_get_usage()/1024/1024;
          echo "&lt;br&gt;";
          unset($cursor);
          $dt = new DateTime($day." 00:00:00", new DateTimeZone($this-&gt;timezone));
          $mongodate = new MongoDate($dt-&gt;getTimestamp());
         // print_r($mongodate);
          $cursor = $dc-&gt;findOne(array('keyword' =&gt; $keyword, 'date' =&gt; $mongodate));
  
  
          echo "Cursor loaded Doc (".$cursor['_id'].") : ";
          echo memory_get_usage()." in MB : "; 
          echo memory_get_usage()/1024/1024;
          echo "&lt;br&gt;";
  </code></pre>
  
  <p>** Echos True Memory Usage**</p>
  
  <pre><code>3932160 in MB : 3.75
  Cursor geladen Doc (534cdee3c30fd1b8ee0bb641) : 218305980 in MB : 208.1928062439
  </code></pre>
  
  <p><strong>Code with Debug echos True Memory Usage:</strong></p>
  
  <pre><code>        echo memory_get_usage(true)." in MB : "; 
          echo memory_get_peak_usage(true)/1024/1024;
          echo "&lt;br&gt;";
          unset($cursor);
          $dt = new DateTime($day." 00:00:00", new DateTimeZone($this-&gt;timezone));
          $mongodate = new MongoDate($dt-&gt;getTimestamp());
         // print_r($mongodate);
          $cursor = $dc-&gt;findOne(array('keyword' =&gt; $keyword, 'date' =&gt; $mongodate));
          /*
          echo "&lt;pre&gt;";
          print_r($cursor);
          echo "&lt;/pre&gt;";
          */
  
          echo "Cursor loaded Doc (".$cursor['_id'].") : ";
          echo memory_get_usage(true)." in MB : "; 
          echo memory_get_peak_usage(true)/1024/1024;
          echo "&lt;br&gt;";
  </code></pre>
  
  <p>** Echos True Memory Usage**</p>
  
  <pre><code>3932160 in MB : 3.75
  Cursor loaded Doc (534cdee3c30fd1b8ee0bb641) : 218628096 in MB : 224.5
  </code></pre>
  
  <p>So only one Documents causes an encrease by over 200 MB of memory.</p>
  
  <pre><code>bitrs3:PRIMARY&gt; var doc = db.dailies.findOne({"_id" : ObjectId("534cdee3c30fd1b8ee0bb641")})
  bitrs3:PRIMARY&gt; Object.bsonsize(doc)
  16754823
  </code></pre>
  
  <p>The document loaded is truely not small, it has 16754823 Bytes so reaches the maximum Bson Size of 16 MB</p>
  
  <p>Still I am wondering if it is normal that the findOne + cursor operation which creates an array out of the results needs so much memory.</p>