Laravel-mongodb: get by random order

Created on 19 Apr 2018  路  5Comments  路  Source: jenssegers/laravel-mongodb

Laravel has inRandomOrder() method on collections.

How to get documents by random order here?

Is it possible?

enhancement

Most helpful comment

Got the same problem and just found out that MongoDB has no built-in way to return random documents.

There is something similar though, from version 3.2 (https://docs.mongodb.com/manual/reference/operator/aggregation/sample/) but as the docs say, it might return more than once the same record on a request.

Used it on my code like;
$result = myModel::raw(function($collection){ return $collection->aggregate([ ['$sample' => ['size' => 3]] ]); })

All 5 comments

Thanks @xxCryptoxx , but non of this worked.

I got this with both eloquent or query builder.

[MongoDB\Driver\Exception\ServerException] bad sort specification

same question

Got the same problem and just found out that MongoDB has no built-in way to return random documents.

There is something similar though, from version 3.2 (https://docs.mongodb.com/manual/reference/operator/aggregation/sample/) but as the docs say, it might return more than once the same record on a request.

Used it on my code like;
$result = myModel::raw(function($collection){ return $collection->aggregate([ ['$sample' => ['size' => 3]] ]); })

Got the same problem and just found out that MongoDB has no built-in way to return random documents.

There is something similar though, from version 3.2 (https://docs.mongodb.com/manual/reference/operator/aggregation/sample/) but as the docs say, it might return more than once the same record on a request.

Used it on my code like;
$result = myModel::raw(function($collection){ return $collection->aggregate([ ['$sample' => ['size' => 3]] ]); })

Thank u!! worked like a charm.
adding a condition:
raw(function($collection){ return $collection->aggregate([ ['$sample' => ['size' => 5]] ]); })->where('Active','=',true);

@Didstriker Thank you 馃懚馃徏

Was this page helpful?
0 / 5 - 0 ratings