Retrieving array of ids in Mongoid

前端 未结 4 469
余生分开走
余生分开走 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 15:57

    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)
    

提交回复
热议问题