Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find random record in Mongoose [duplicate]

How can I find random records in MongoDB?

I found multiple articles here on StackOverflow, but I couldn't understand them. Like for example:

db.yourCollection.find().limit(-1).skip(yourRandomNumber).next() 

How would I execute it in my code? (collection is User)

User.findOne(RANDOM PLAYER).then(result) {     console.log(result); } 
like image 895
maria Avatar asked Sep 01 '16 17:09

maria


2 Answers

The idea behind getting a random record is to query all the matching records but just get one. This is what findOne() does without any criteria given.

Then you will want to pick a random entry in all the possible matches. This is done by:

  1. Find out how many possible entries there could be - we use count() on the collection for this. Note that, as mentioned in comments, count is deprecated in version 4 and one should use estimatedDocumentCount or countDocuments instead. The different lies in precision/memory usage amongst other things. Here's a SO post discussing it a bit.

  2. Come up with a random number within our count.

  3. Use skip() to "skip" to the desired match and return that.

Here's a snippet as modified from this SO answer:

// Get the count of all users User.count().exec(function (err, count) {    // Get a random entry   var random = Math.floor(Math.random() * count)    // Again query all users but only fetch one offset by our random #   User.findOne().skip(random).exec(     function (err, result) {       // Tada! random user       console.log(result)      }) }) 
like image 191
cyberwombat Avatar answered Sep 30 '22 15:09

cyberwombat


To get random document(s) from mongodb by using mongoose.

    limitrecords=10;      function getRandomArbitrary(min, max) {       return Math.ceil(Math.random() * (max - min) + min);     }      var userschema = new Schema({       name: String     });      User = mongoose.model('User', userschema);      User.count({your_query},function(err,count){         var skipRecords = getRandomArbitrary(1, count-limitrecords);         query.skip(skipRecords); // Random Offset         query.exec(function(err,result){          console.log(result);  // 10 random users         });      }); 

This is an example for 10 random records, you can set "limitrecords" according to your requirement.

Thanks!

like image 26
Rahul Thakkar Avatar answered Sep 30 '22 15:09

Rahul Thakkar