2

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 query interface. Any ideas?

code-gijoe
  • 6,949
  • 14
  • 67
  • 103
Peder
  • 2,739
  • 3
  • 31
  • 33

1 Answers1

3

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.

Community
  • 1
  • 1
Matt
  • 17,290
  • 7
  • 57
  • 71