问题
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