37

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);
}
Kaspar Lee
  • 5,446
  • 4
  • 31
  • 54
maria
  • 207
  • 5
  • 22
  • 56

2 Answers2

75

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) 
    })
})
cyberwombat
  • 38,105
  • 35
  • 175
  • 251
1

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!

  • 2
    `ReferenceError: query is not defined` - where are you setting query from? – Luke Brown Jun 11 '19 at 11:20
  • Luke: https://mongoosejs.com/docs/api/query.html#query_Query That is a query. So something like `User.find()` or `User.where({ name: 'vonderful' })`. – Nebulosar Jul 13 '21 at 12:02
  • Heads up. That this answer returns a random start of the find but the sequence will always be the same. Original: [ 1 2 3 4 5 ] with limitrecords=3, possible returns: [ 1, 2, 3 ], [2 3 4 ],[ 3 4 5 ] – Ezequiel Santiago Sánchez Sep 06 '21 at 05:46