title: Meteor,Mongo query find every nth document
body: <p>I use time stamps in my collection so every document has a time stamp, user want's to get documents from "<strong>ts1</strong>" (time stamp 1) to "<strong>ts2</strong>" (time stamp 2), however there a too many documents in that interval so I wan't to return only every nth, for example if there is 100000 documents, I need to display 1000 documents, so 100000/1000=100. every 100th document.</p>
  
  <p>Is this possible, and how could I achieve this.</p>
  
  <p>PS. I need to query this inside Meteor publish method.</p>
  
  <p>Here's what I'v got so far:</p>
  
  <pre><code>Meteor.publish('documents-chunk', function (from, to) {
      //get find documents count and get nth
      var count = Documents.find({time: {$gte: from, $lte: to}}).count();
      if (count &gt; 2000) {
          var nth = Math.round(count / 1000);
          return Documents.find(/*query every nth*/);
      }
      return Documents.find({time: {$gte: from, $lte: to}});
  });
  </code></pre>
  
  <p><strong>SOLUTION:</strong></p>
  
  <p>I ~solved this problem using answer from Matt K.</p>
  
  <p>This is what I'v done: first I modified my collection and added additional "id" field: </p>
  
  <p>**</p>
  
  <h2>1.</h2>
  
  <p>**</p>
  
  <pre><code>Document.find({}, {sort: {time: 1}}).forEach(function (c, i) {
      Document.update(c, {$set: {id: i + 1}});
      console.log(i + 1);
  });
  </code></pre>
  
  <p>This collection had little less than 1,5M records so it took some time, (also to note, I had to add index {time: 1} to this collection otherwise it would crash the database)</p>
  
  <p>**</p>
  
  <h2>2.</h2>
  
  <p>**</p>
  
  <pre><code>Meteor.publish('documents-chunk', function (from, to) {
      var nth = Math.round(Documents.find({time: {$gte: from, $lte: to}}, {sort: {time: 1}}).count() / 1000);
      return Documents.find({time: {$gte: from, $lte: to, $mod: [nth, 0]}}, {sort: {time: 1}});
  });
  </code></pre>
  
  <p>This worked for me, and now I get the result I needed;</p>
  
  <p>I'v read at <a href="http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/" rel="nofollow">http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/</a> that this kinda approach is not recommended. But at this point of time I could not find any other solution to this problem, though I found that it is requested <a href="https://jira.mongodb.org/browse/SERVER-2397" rel="nofollow">https://jira.mongodb.org/browse/SERVER-2397</a> so maybe in future there will be cleaner solution, but for now it works.</p>