Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid: find through Array of ids

I've fetched a number of ids through MapReduce. I've sorted those ids by some criteria and now I need to get those objects in this particular order:

MyModel.find(ids)

Right? But it returns objects not in the order ids are stored. Looks like this is just the same as

MyModel.where(:_id.in => ids)

which won't return fetched objects in just the same order as stored ids.

Now I can do this

ids.map{|id| MyModel.find(id)}

which will do the job but it will knock the database many many times.

like image 507
fl00r Avatar asked Sep 23 '11 18:09

fl00r


2 Answers

You can do the ordering by hand after you have all your objects. Something like this:

ordering = { }
ids.each_with_index { |id, i| ordering[id] = i }
objs = MyModel.find(ids).sort_by { |o| ordering[o.id] }
like image 72
mu is too short Avatar answered Nov 15 '22 18:11

mu is too short


Was working on a similar problem and found a bit more concise solution:

objs = MyModel.find(ids).sort_by{|m| ids.index(m.id) }

basically just using the sort block to snag the index of the the element.

like image 42
njorden Avatar answered Nov 15 '22 18:11

njorden