The following code return a error
$articles = Article::orderBy(DB::raw('RAND()'))->get();
Illegal offset type in /Mongodb/Query/Builder.php Line 284
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} }])
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();