Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving array of ids in Mongoid

Tags:

ruby

mongoid

how do you retrieve an array of IDs in Mongoid?

arr=["id1","id2"] User.where(:id=>arr) 

You can do this easily if you are retrieving another attribute

User.where(:nickname.in=>["kk","ll"]) 

But I am wondering how to do this in mongoid -> this should be a very simple and common operation

like image 824
meow Avatar asked Dec 08 '10 11:12

meow


2 Answers

Remember that the ID is stored as :_id and not :id . There is an id helper method, but when you do queries, you should use :_id:

User.where(:_id.in => arr) 

Often I find it useful to get a list of ids to do complex queries, so I do something like:

user_ids = User.only(:_id).where(:foo => :bar).distinct(:_id) Post.where(:user_id.in => user_ids) 
like image 117
bowsersenior Avatar answered Sep 18 '22 18:09

bowsersenior


Or simply:

arr = ['id1', 'id2', 'id3'] User.find(arr) 
like image 31
gjb Avatar answered Sep 18 '22 18:09

gjb