Red
Red

Reputation: 2246

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?

Upvotes: 1

Views: 545

Answers (2)

Brian Hempel
Brian Hempel

Reputation: 9094

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

Upvotes: 0

Andrew Orsich
Andrew Orsich

Reputation: 53685

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.

Upvotes: 2

Related Questions