Skip to content Skip to sidebar Skip to footer

Mongodb: Pulling Multiple Random Documents From A Collection

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?

Solution 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.

Solution 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

Post a Comment for "Mongodb: Pulling Multiple Random Documents From A Collection"