我想找到许多只做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)
根据您的要求更改限制(),希望这将有助于....
谢谢
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)