Retrieving array of ids in Mongoid

前端 未结 4 480
余生分开走
余生分开走 2020-12-28 15:11

how do you retrieve an array of IDs in Mongoid?

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

You can do this eas

4条回答
  •  一个人的身影
    2020-12-28 16:03

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

提交回复
热议问题