Mongoid random document

前端 未结 9 1397
迷失自我
迷失自我 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:22

    The best solution is going to depend on the expected size of the collection.

    For tiny collections, just get all of them and .shuffle.slice!

    For small sizes of n, you can get away with something like this:

    result = (0..User.count-1).sort_by{rand}.slice(0, n).collect! do |i| User.skip(i).first end
    

    For large sizes of n, I would recommend creating a "random" column to sort by. See here for details: http://cookbook.mongodb.org/patterns/random-attribute/ https://github.com/mongodb/cookbook/blob/master/content/patterns/random-attribute.txt

提交回复
热议问题