title: MongoDb: $sort by $in
body: <p>I am running a mongodb <code>find</code> query with an <code>$in</code> operator:</p>
  
  <pre><code>collection.find({name: {$in: [name1, name2, ...]}})
  </code></pre>
  
  <p>I would like the results to be sorted in the same order as my name array: <code>[name1, name2, ...]</code>. How do I achieve this?</p>
  
  <p>Note: I am accessing MongoDb through pymongo, but I don't think that's of any importance.</p>
  
  <p>EDIT: as it's impossible to achieve this natively in MongoDb, I ended up using a typical Python solution:</p>
  
  <pre><code>names = [name1, name2, ...]
  results = list(collection.find({"name": {"$in": names}}))
  results.sort(key=lambda x: names.index(x["name"]))
  </code></pre>