Laravel-mongodb: Return random record

Created on 10 Jan 2014  路  4Comments  路  Source: jenssegers/laravel-mongodb

The following code return a error

$articles = Article::orderBy(DB::raw('RAND()'))->get();

Illegal offset type in /Mongodb/Query/Builder.php Line 284

Most helpful comment

if number of articles equals to random number than it will gives null. should use

$article = Article::take(1)->skip(rand(0,$noOfArticles-1))->first();

All 4 comments

Is that even possible in MongoDB?

It's not possible in MongoDB. If you only need one article then you can around it by taking one and skipping a random number of records. Not at all good for performance so use it wisely:

$article = Article::take(1)->skip(rand(0,$noOfArticles))->first();

if number of articles equals to random number than it will gives null. should use

$article = Article::take(1)->skip(rand(0,$noOfArticles-1))->first();

if mongo 3.2:

db.collection.aggregate([{$sample: {size: 5} }])

Was this page helpful?
0 / 5 - 0 ratings

Related issues

naveedyasin picture naveedyasin  路  3Comments

BlakeGardner picture BlakeGardner  路  3Comments

phuocduy1988 picture phuocduy1988  路  3Comments

Idnan picture Idnan  路  3Comments

sanjay1688 picture sanjay1688  路  3Comments