How to find random record in Mongoose

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) 
    })
})

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!