6

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?

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
Ruben Yeghikyan
  • 497
  • 2
  • 6
  • 19
  • I have written a package https://www.npmjs.com/package/unique-random-docs that fix duplication issues and return only unique random docs npm i unique-random-docs feel free to check it out! – Detoner Mar 01 '21 at 10:18

2 Answers2

14

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

nish71
  • 275
  • 1
  • 7
4

Pass a function that returns a Boolean value in the find parameter:

db.collection.find(function () {return Boolean(Math.floor(Math.random() * 2))})

You can see how many records were returned using count():

db.collection.find(...).count()

Also, if you want to limit the document cout use limit():

db.collection.find(...).limit(/* how many? */)
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474