如何在猫鼬中找到随机记录 [英] How to find random record in Mongoose
问题描述
如何在 MongoDB 中查找随机记录?
How can I find random records in MongoDB?
我在 StackOverflow 上找到了多篇文章,但我无法理解它们.例如:
I found multiple articles here on StackOverflow, but I couldn't understand them. Like for example:
db.yourCollection.find().limit(-1).skip(yourRandomNumber).next()
我将如何在我的代码中执行它?(集合是User
)
How would I execute it in my code? (collection is User
)
User.findOne(RANDOM PLAYER).then(result) {
console.log(result);
}
推荐答案
获取随机记录背后的想法是查询所有匹配的记录,但只获取一个.这就是 findOne()
在没有给出任何标准的情况下所做的.
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:
找出可能有多少可能的条目 - 为此,我们在集合上使用
count()
.请注意,如评论中所述,count
在第 4 版中已弃用,应使用 estimatedDocumentCount 或 countDocuments 代替.不同之处在于精度/内存使用等.这是一篇SO 的帖子,对其进行了一些讨论.
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.
在我们的计数范围内找出一个随机数.
Come up with a random number within our count.
使用 skip()
来跳过"到所需的匹配项并返回.
Use skip()
to "skip" to the desired match and return that.
这是从这个SO answer修改而来的片段:
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)
})
})
这篇关于如何在猫鼬中找到随机记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!