The way to do this is to use the identity map in mongoid. There are more details on this here: http://mongoid.org/en/mongoid/docs/identity_map.html
But the short and simple way to do this is in your mongoid.yml
set the following property:
identity_map_enabled: true
Then search for the following: Player.find(@draftees)
And this will return your draftees in the order of the array that you passed in. One caveat is that it won't return duplicates so your @draftees
array above if used would return only two values (the order is based on the first appearance of the id, so it will return the player with id "52f4fd9f52e39bc0c15674ea" first and then the player with id "52f4fd9f52e39bc0c15674eb"). So you will have to recreate the duplicates via some sort of abstraction.
Here is one possible way to do this, and it was inspired by a comment posted by @muistooshort below:
In your User
class add the following function
def get_draftee_list
players = Player.find(self.draftees).each_with_object({}) { |p, h| h[p.id] = p }
return self.draftees.map { |id| players[Moped::BSON::ObjectId.from_string(id)] }
end
Note: This was tested on Mongoid 3
This should solve your problem since each call to raw_data.find(id)
is searching the result set from your the initial query which is stored in memory and not making another query to the db