fl00r
fl00r

Reputation: 83680

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.

Upvotes: 10

Views: 5833

Answers (2)

njorden
njorden

Reputation: 2606

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.

Upvotes: 12

mu is too short
mu is too short

Reputation: 434945

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] }

Upvotes: 11

Related Questions