Để lấy danh sách 10 bản ghi sắp xếp ngẫu nhiên trong MongoDB (order by rand) chúng ta sử dụng câu lệnh mongo shell sau:
db.posts.aggregate([
{ $sample : { size: 10 } }
])

Nếu các bạn muốn filter (where) theo một điệu kiện nhất định. VD: column site = ‘vinasupport.com‘ thì dùng lệnh mongo shell sau đây.
db.posts.aggregate([
{ $match : { site: 'vinasupport.com' } },
{ $sample : { size: 10 } }
])
Trường hợp các bạn sử dụng PHP Laravel với MongoDB thì tham khảo đoạn code sau:
Post::raw(
function($collection)
{
return $collection->aggregate([
// Filter by site
['$match' => ['site' => 'vinasupport.com'],
['$sample' => ['size' => 10]]
]);
}
);
Nguồn vinasupport.com