Retrieving array of ids in Mongoid

2019-02-02 09:29发布

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

标签: ruby mongoid
4条回答
我命由我不由天
2楼-- · 2019-02-02 09:39

Or simply:

arr = ['id1', 'id2', 'id3']
User.find(arr)
查看更多
劫难
3楼-- · 2019-02-02 09:44

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)
查看更多
Lonely孤独者°
4楼-- · 2019-02-02 10:00
user_ids = User.only(:_id).where(:foo => :bar).map(&:_id)
Post.where(:user_id.in => user_ids)

The solution above works fine when amount of users is small. But it will require a lot of memory while there are thousands of users.

User.only(:_id).where(:foo => :bar).map(&:_id)

will create a list of User objects with nil in each field except id.

The solution (for mongoid 2.5):

User.collection.master.where(:foo => :bar).to_a.map {|o| o['_id']}
查看更多
SAY GOODBYE
5楼-- · 2019-02-02 10:01

The above method suggested by browsersenior doesn't seem to work anymore, at least for me. What I do is:

User.criteria.id(arr)
查看更多
登录 后发表回答