title: Mongodb: Query on the last N documents(some portion) of a collection only
body: <p>In my collection that has say 100 documents, I want to run the following query:</p>
  <pre class="lang-js prettyprint-override"><code>collection.find({&quot;$text&quot; : {&quot;$search&quot; : &quot;some_string&quot;})
  </code></pre>
  <p>Assume that a suitable &quot;text&quot; index already exists and thus my question is : <strong>How can I run this query on the last 'n' documents only?</strong></p>
  <p>All the question that I found on the web ask how to <em>get</em> the last n docs. Whereas My question is how to <em>search</em> on the last n docs only?</p>
  <p>More generally my question is How can I run a mongo query on some portion say 20% of a collection.</p>
  <p><strong>What I tried</strong></p>
  <p>Im using pymongo so I tried to use skip() and limit() to get the last n documents but I didn't find a way to perform a query on cursor that the above mentioned function return.</p>
  <p>After @hhsarh's anwser here's what I tried to no avail</p>
  <pre class="lang-py prettyprint-override"><code># here's what I tried after initial answers
  recents = information_collection.aggregate([
                  {&quot;$match&quot; : {&quot;$text&quot; : {&quot;$search&quot; : &quot;healthline&quot;}}},
                  {&quot;$sort&quot; : {&quot;_id&quot; : -1}},
                  {&quot;$limit&quot; : 1},
              ])
  </code></pre>
  <p>The result is still coming from the whole collection instead of just the last record/document as the above code attempts.</p>
  <p>The last document doesn't contain &quot;healthline&quot; in any field therefore the intended result of the query should be empty []. But I get a documents.</p>
  <p>Please can someone tell how this can be possible</p>