How to find random record in Mongoose [duplicate]

2020-02-25 07:51发布

How can i find random records in mongodb?

i found multiple articles here on stackoverflow, but i couldnt 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);
}

2条回答
贪生不怕死
2楼-- · 2020-02-25 08:21

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.

  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) 
    })
})
查看更多
▲ chillily
3楼-- · 2020-02-25 08:23

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!

查看更多
登录 后发表回答