title: MongoDB aggregate to find first document with value greater than n
body: <p>Given a LARGE (hundreds of thousands) collection of event documents (see below for example), what is the most performant method to retrieve the <em>first</em> event with an _id <em>greater than</em> (<em>n</em>) ?</p>
  
  <h3>Example Document</h3>
  
  <pre class="lang-js prettyprint-override"><code>{ 
    _id: NumberLong(352757), // Uniqueness guaranteed
    type: "BallDropped",
    createdAt: "2014-01-01T00:00:00Z",
    // ... followed by dynamic properties of unknown size
  }
  </code></pre>
  
  <h3>Current Implementation</h3>
  
  <p>Given a collection of many events, retrieve the <em>first</em> event with an _id greater than 35.</p>
  
  <p>First, retrieve the <em>id</em> of the event using aggregate.</p>
  
  <p>I do this assuming that the projection phase (return just the id) will be more performant than cycling over full documents of unknown size.</p>
  
  <pre class="lang-js prettyprint-override"><code>db.events.aggregate(
    { $project: { _id: 1 } },
    { $match: { _id: { $gt: NumberLong(35) } } },
    { $sort: { _id: 1 } },
    { $limit: 1 }
  )
  </code></pre>
  
  <p>Then, I call findOne with the returned _id to retrieve that document.</p>
  
  <p>What are your thoughts?</p>