如何在mongodb中找到随机记录

Rub*_*yan 5 mongodb

我想找到许多只做1个查询的随机记录.

我试过了:

var count = db.collections.count()
var rand = function(){return Math.floor( Math.random() * count )}

db.collection.find().limit(-1).skip(rand()).next();
Run Code Online (Sandbox Code Playgroud)

但是这只返回一个文档.我需要获得更多随机记录.

我怎样才能做到这一点?

小智 12

另一种方式来实现

db.Colletion.find().limit( 50 ).skip( _rand() * db.Collection.count() )
Run Code Online (Sandbox Code Playgroud)

根据您的要求更改限制(),希望这将有助于....

谢谢

  • 这太低效了.首先获取所有记录,然后抵消不是正确的方法... (4认同)

Ion*_*zău 4

Boolean传递一个在参数中返回值的函数find

db.collection.find(function () {return Boolean(Math.floor(Math.random() * 2))})
Run Code Online (Sandbox Code Playgroud)

您可以使用以下命令查看返回了多少条记录count()

db.collection.find(...).count()
Run Code Online (Sandbox Code Playgroud)

另外,如果您想限制文档 cout 使用limit()

db.collection.find(...).limit(/* how many? */)
Run Code Online (Sandbox Code Playgroud)

  • 当然,这种事情的速度意味着你永远不应该这样做 (4认同)