【问题标题】:How to find random record in Mongoose [duplicate]如何在猫鼬中找到随机记录[重复]
【发布时间】:2017-01-09 16:48:45
【问题描述】:

如何在 MongoDB 中找到随机记录?

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

db.yourCollection.find().limit(-1).skip(yourRandomNumber).next()

我将如何在我的代码中执行它? (收藏为User

User.findOne(RANDOM PLAYER).then(result) {
    console.log(result);
}

【问题讨论】:

标签: javascript mongodb mongoose


【解决方案1】:

获取随机记录背后的想法是查询所有匹配的记录,但只得到一个。这就是 findOne() 在没有给出任何标准的情况下所做的。

然后,您将希望在所有可能的匹配项中选择一个随机条目。这是由以下人员完成的:

  1. 找出可能有多少条目 - 我们为此在集合中使用count()。请注意,如 cmets 中所述,count 在版本 4 中已弃用,应使用 estimatedDocumentCountcountDocuments 代替。不同之处在于精度/内存使用等。这是一个 SO 的帖子,对此进行了一些讨论。

  2. 在我们的计数范围内找出一个随机数。

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

这是一个从 SO answer 修改而来的 sn-p:

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

【讨论】:

  • 正是我想要的。谢谢!
  • 干得好!!这就是我一直在寻找的。​​span>
  • count() - collection.count 已弃用,将在未来版本中删除。请改用 Collection.countDocuments 或 Collection.estimatedDocumentCount。
【解决方案2】:

使用 mongoose 从 mongodb 获取随机文档。

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

    });

这里以10条随机记录为例,你可以根据自己的需要设置“limitrecords”。

谢谢!

【讨论】:

  • ReferenceError: query is not defined - 你在哪里设置查询?
  • 卢克:mongoosejs.com/docs/api/query.html#query_Query 这是一个查询。比如User.find()User.where({ name: 'vonderful' })
  • 请注意。这个答案返回一个随机开始的查找,但顺序总是相同的。原文:[ 1 2 3 4 5 ] with limitrecords=3,可能返回:[ 1, 2, 3 ], [2 3 4 ],[ 3 4 5 ]
猜你喜欢
  • 2017-06-05
  • 2014-01-13
  • 1970-01-01
  • 2017-07-15
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
相关资源
最近更新 更多