laravel-mongodb icon indicating copy to clipboard operation
laravel-mongodb copied to clipboard

get by random order

Open saeedvz opened this issue 6 years ago • 5 comments

Laravel has inRandomOrder() method on collections.

How to get documents by random order here?

Is it possible?

saeedvz avatar Apr 19 '18 20:04 saeedvz

Thanks @xxCryptoxx , but non of this worked.

I got this with both eloquent or query builder.

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

thureos avatar Aug 23 '18 12:08 thureos

same question

leelijin avatar Sep 21 '18 07:09 leelijin

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]]
    ]);
})

Didstriker avatar Jan 09 '19 11:01 Didstriker

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);

Jaffer2x avatar Feb 21 '19 20:02 Jaffer2x

@Didstriker Thank you 👶🏼

ozgursoy avatar Aug 15 '19 00:08 ozgursoy

Thanks for the provided solution https://github.com/mongodb-php/laravel-mongodb/issues/1493#issuecomment-452664988

GromNaN avatar Aug 28 '23 15:08 GromNaN

@GromNaN Do you think a new method sample() or inRandomOrder() can be added?

See #1967

Giacomo92 avatar Aug 28 '23 20:08 Giacomo92

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.

GromNaN avatar Aug 28 '23 20:08 GromNaN

Ok thanks! Maybe an example can be added on docs.

Giacomo92 avatar Aug 28 '23 20:08 Giacomo92