title: How to handle pagination queries properly with mongodb and php?
body: <p>Am I doing this right? I went to look at some old PHP code w/ MySQL and I've managed to get it to work, however I'm wondering if there's a much "cleaner" and "faster" way of accomplishing this.</p>
  
  <p>First I would need to get the total number of "documents"</p>
  
  <pre><code>$total_documents = $collection-&gt;find(array("tags" =&gt; $tag, 
          "seeking" =&gt; $this-&gt;session-&gt;userdata('gender'), 
          "gender" =&gt; $this-&gt;session-&gt;userdata('seeking')))-&gt;count();
  
  $skip = (int)($docs_per_page * ($page - 1));
  $limit = $docs_per_page;
  $total_pages = ceil($total_documents / $limit);
  </code></pre>
  
  <p>// Query to populate array so I can display with pagination</p>
  
  <pre><code>$data['result'] = $collection-&gt;find(array("tags" =&gt; $tag, 
          "seeking" =&gt; $this-&gt;session-&gt;userdata('gender'), 
          "gender" =&gt; $this-&gt;session-&gt;userdata('seeking')))-&gt;limit($limit)-&gt;skip($skip)-&gt;sort(array("_id" =&gt; -1));
  </code></pre>
  
  <p>My question is, can I run the query in one shot? I'm basically running the same query twice, except the second time I'm passing the value to skip between records.</p>
  
  <p>-- New code ...</p>
  
  <p>Ok, unless someone knows of another way to do this (if it's possible), I'm going to say it's not doable. With that said, I changed the way I run my queries through mongodb, which yielded better looking code. ;-) I was trying to minimize the trips to the DB, but oh well hopefully this doesn't take a performance hit. My other attempt was to count the number of elements in the array, but quickly found out that wouldn't work since the $limit &amp; $skip parameters would give ITS total number of docs.</p>
  
  <pre><code>$skip = (int)($docs_per_page * ($page - 1));
  $limit = $docs_per_page;
  
  $query = array("loc" =&gt; array('$near' =&gt; array('lat' =&gt; $latitude, 'lon' =&gt; $longitute) ),
          "tags" =&gt; $tag, "seeking" =&gt; $this-&gt;session-&gt;userdata('gender'),
          "gender" =&gt; $this-&gt;session-&gt;userdata('seeking'));
  
  $fields = array("username", "zipcode", "tags", "birth_date");
  $total_documents = $collection-&gt;find($query, array("_id"))-&gt;count();
  $data['result'] = $collection-&gt;find($query, $fields)-&gt;limit($limit)-&gt;skip($skip);
  </code></pre>