MongoDB: Pulling multiple random documents from a collection

六月ゝ 毕业季﹏ 提交于 2019-12-11 05:17:17

问题


I need to pull multiple random documents from a collection in MongoDB. I don't want to ad a new key to my documents or use a map reduce. Any suggestions?


回答1:


You can generate random skip in range from 0 up to collection items count and then load documents:

db.items.find().skip(randonNumberHere).limit(1);

But, such approach because less and less efficient for a big collections, because each time when you use skip mongodb iterate from first to skip item.




回答2:


If the collection isn't ridiculously large...

all_ids = MyModel.collection.distinct(:_id)
@my_models = MyModel.find(all_ids.sample(100)) # or .shuffle.take(100) in 1.8.7


来源:https://stackoverflow.com/questions/9315375/mongodb-pulling-multiple-random-documents-from-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!