laravel-mongodb
laravel-mongodb copied to clipboard
get by random order
Laravel has inRandomOrder() method on collections.
How to get documents by random order here?
Is it possible?
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 👶🏼
Thanks for the provided solution https://github.com/mongodb-php/laravel-mongodb/issues/1493#issuecomment-452664988
@GromNaN Do you think a new method sample() or inRandomOrder() can be added?
See #1967
We are going to work on an aggregation builder in the coming month, which will provide a lot more features with an unified interface. I don't think an opininiated method is necessary at this point.
Ok thanks! Maybe an example can be added on docs.