title: Mongo: sort documents by array of ids
body: <p>Say you have an array of document ids stored elsewhere (e.g. in Redis sorted set).</p>
  
  <p>What is the most efficient way of querying Mongo documents with <code>{ _id: { $in: ids }}</code> and having the results sorted in the same ordering as it was in <code>ids</code> array?</p>
  
  <h3>Example</h3>
  
  <pre><code>var ids = [3,2,1,6,7];
  
  db.records.find({ _id: { $in: ids }})
   .sort({ 
     // ???
   });
  
  // expecting [{_id: 3}, {_id: 2}, {_id: 1}, {_id: 6}, {_id: 7}]
  </code></pre>
  
  <p>P.S. I know I can do the sorting in application, but I wonder, if it could be done with more efficiency at the backend.</p>