Mongo: sort documents by array of ids

mongodb, sorting

Solution

You cannot do it in MongoDB right now. There is an open issue in jira.

SERVER-7528

Problem

Say you have an array of document ids stored elsewhere (e.g. in Redis sorted set). What is the most efficient way of querying Mongo documents with `{ _id: { $in: ids }}` and having the results sorted in the same ordering as it was in `ids` array? Example ``` 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}] ``` 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.

Original source