Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find random records in mongodb [duplicate]

Tags:

mongodb

I want find many random records doing only 1 query.

I tried:

var count = db.collections.count()
var rand = function(){return Math.floor( Math.random() * count )}

db.collection.find().limit(-1).skip(rand()).next();

But this returns only one document. I need to get more random records.

How can I do this?

like image 292
Ruben Yeghikyan Avatar asked Dec 25 '13 14:12

Ruben Yeghikyan


1 Answers

Another way to achive

db.Colletion.find().limit( 50 ).skip( _rand() * db.Collection.count() )

change the limit() as per your requirement, Hope this will Help....

Thanks

like image 111
nish71 Avatar answered Sep 23 '22 08:09

nish71