Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get by random order #1493

Closed
saeedvz opened this issue Apr 19, 2018 · 9 comments
Closed

get by random order #1493

saeedvz opened this issue Apr 19, 2018 · 9 comments

Comments

@saeedvz
Copy link

saeedvz commented Apr 19, 2018

Laravel has inRandomOrder() method on collections.

How to get documents by random order here?

Is it possible?

@thureos
Copy link

thureos commented Aug 23, 2018

Thanks @xxCryptoxx , but non of this worked.

I got this with both eloquent or query builder.

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

@leelijin
Copy link

same question

@Didstriker
Copy link

Didstriker commented Jan 9, 2019

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

@Jaffer2x
Copy link

Jaffer2x commented Feb 21, 2019

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

@ozgursoy
Copy link

@Didstriker Thank you 👶🏼

@GromNaN
Copy link
Member

GromNaN commented Aug 28, 2023

Thanks for the provided solution #1493 (comment)

@GromNaN GromNaN closed this as completed Aug 28, 2023
@Giacomo92
Copy link

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

See #1967

@GromNaN
Copy link
Member

GromNaN commented Aug 28, 2023

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.

@Giacomo92
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

9 participants