Retrieve list of mongo documents by ids preserving order
Which is the best way to retrieve a list of mongodb documents using mongoid in the order specified in the list.
My current solution is:
docs = Doc.where(:_id.in => ids).sort { |x, y| ids.index(x.id) <=> ids.index(y.id) }
It seems there should be a better solution for this using mongoid que开发者_开发技巧ry interface. Any ideas?
If the number of ids is small you might get away with this (no need to sort it though):
docs = ids.map { |id| Doc.find(id) }
The drawback is of course that it will still go to the database for every document.
The closest method I could find is Doc.criteria.for_ids(ids)
but it will not honor the order of the ids and fetch every document only once. See this question.
精彩评论