Mongoid random document

前端 未结 9 1399
迷失自我
迷失自我 2021-02-06 00:49

Lets say I have a Collection of users. Is there a way of using mongoid to find n random users in the collection where it does not return the same user twice? For now lets say

9条回答
  •  情歌与酒
    2021-02-06 01:03

    You can do this by

    1. generate random offset which will further satisfy to pick the next n elements (without exceeding the limit)
    2. Assume count is 10, and the n is 5
    3. to do this check the given n is less than the total count
    4. if no set the offset to 0, and go to step 8
    5. if yes, subtract the n from the total count, and you will get a number 5
    6. Use this to find a random number, the number definitely will be from 0 to 5 (Assume 2)
    7. Use the random number 2 as offset
    8. now you can take the random 5 users by simply passing this offset and the n (5) as a limit.
    9. now you get users from 3 to 7

    code

    >> cnt = User.count
    => 10
    >> n = 5
    => 5
    >> offset = 0
    => 0
    >> if n>    offset = rand(cnt-n)
    >>  end
    >> 2
    >> User.skip(offset).limit(n)
    

    and you can put this in a method

    def get_random_users(n)
      offset = 0
      cnt = User.count
      if n < cnt
        offset = rand(cnt-n)
      end
      User.skip(offset).limit(n)
    end
    

    and call it like

    rand_users = get_random_users(5)
    

    hope this helps

提交回复
热议问题