如何在Mongoose中找到随机记录 [英] How to find random record in Mongoose

查看:635
本文介绍了如何在Mongoose中找到随机记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

How can i find random records in mongodb?

我在stackoverflow上找到了多篇文章,但我无法理解它们。
例如:

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


推荐答案

获取随机背后的想法记录是查询所有匹配的记录,但只获得一个。这是 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:


  1. 找出可能有多少条目 - 我们使用 count( )

  1. 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.

使用 skip()跳过到所需的匹配并返回。

Use skip() to "skip" to the desired match and return that.

以下是根据此 SO回答修改的代码段:

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

这篇关于如何在Mongoose中找到随机记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆