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?
Asked
Active
Viewed 519 times
1
-
2refer to http://stackoverflow.com/questions/2824157/random-record-from-mongodb – Drake Guan Feb 16 '12 at 17:34
-
1I hear you! I don't think the application-level options are very good. Luckily, there is a [feature request to get random items from a collection](https://jira.mongodb.org/browse/SERVER-533) in the MongoDB ticket tracker. If implemented natively, it would likely be the most efficient option. (If you want the feature, go vote it up.) – David J. Jun 17 '12 at 02:38
2 Answers
2
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.
Andrew Orsich
- 51,367
- 16
- 136
- 133
0
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
Brian Hempel
- 8,504
- 2
- 22
- 19