Random record from MongoDB

后端 未结 27 1897
栀梦
栀梦 2020-11-22 01:22

I am looking to get a random record from a huge (100 million record) mongodb.

What is the fastest and most efficient way to do so? The data is already t

27条回答
  •  清酒与你
    2020-11-22 01:33

    If you're using mongoid, the document-to-object wrapper, you can do the following in Ruby. (Assuming your model is User)

    User.all.to_a[rand(User.count)]
    

    In my .irbrc, I have

    def rando klass
        klass.all.to_a[rand(klass.count)]
    end
    

    so in rails console, I can do, for example,

    rando User
    rando Article
    

    to get documents randomly from any collection.

提交回复
热议问题