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);
}
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:
Find out how many possible entries there could be - we use
count()
on the collection for this.Come up with a random number within our count.
Use
skip()
to "skip" to the desired match and return that.Here's a snippet as modified from this SO answer:
To get random document(s) from mongodb by using mongoose.
This is an example for 10 random records, you can set "limitrecords" according to your requirement.
Thanks!