title: Retrieve unique random items from a mongodb collection?
body: <p>I run an IRC bot and I have a function which returns 1 random url using Math.random at the moment, from my Mongodb collection.</p>
  
  <p>I would like to refactor it to return x number of unique items, and for each subsequent invocation of the url fetching command <code>.getlinks</code> I would like that it keeps everything unique, so that a user doesn't see the same link unless all the possible links have been already returned.</p>
  
  <p>Is there some algorithm or native mongodb function I could use for this?</p>
  
  <p>Here's a sample scenario:</p>
  
  <p>I have a total of 9 records in the collection. They have a <code>_id</code> and <code>url</code> field. </p>
  
  <pre><code>user a: .getlinks()
  bot returns: http://unique-link-1, http://unique-link-2, http://unique-link-3, http://unique-link-4
  
  user a: .getlinks()
  bot returns: http://unique-link-5, http://unique-link-6, http://unique-link-7, http://unique-link-8
  
  user a: .getlinks()
  bot returns: http://unique-link-9, http://unique-link-6, http://unique-link-1, http://unique-link-3
  </code></pre>
  
  <p>Background information:</p>
  
  <ul>
  <li>There's a total of about 200 links. I estimate that will grow to around 5000 links by the end of next year.</li>
  </ul>
  
  <p>Currently the only thing I can think of is keeping an array of all returned items, and grabbing all items from the collection at once and getting a random one 4 times and making sure it's unique and hasn't been shown already.</p>
  
  <pre><code>var shown = [], amountToReturn = 4;
  function getLinks() {
     var items = links.find(), returned = [];
     for ( var i = 0; i&lt;amountToReturn; i++ ) {
        var rand = randItem( items );
        if ( shown.indexOf( rand.url ) == -1 &amp;&amp; shown.length &lt; items.length ) ) {
           returned.push( rand.url );
        }
     }
     message.say( returned.join(',') );
  }
  </code></pre>