Để lấy bản ghi ngẫu nhiên, dùng hàm aggregate với $sample. Cú pháp:
db.yourCollectionName.aggregate([{$sample:{size:1}}]);
Tạo collection employeeInformation:
>db.employeeInformation.insert({"EmployeeId":1,"EmployeeName":"Maxwell","EmployeeAge":26});
WriteResult({ "nInserted" : 1 })
... (thêm 4 bản ghi nữa: David, Carol, Bob, Sam) ...
Hiển thị tất cả:
> db.employeeInformation.find().pretty();
Lấy bản ghi ngẫu nhiên:
> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();
Kết quả ví dụ (ngẫu nhiên):
{ "_id" : ObjectId("5c6d30bb734e98fc0a434ae9"), "EmployeeId" : 5, "EmployeeName" : "Sam", "EmployeeAge" : 27 }
Chạy lại lần nữa cho kết quả khác:
> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();
Kết quả: EmployeeId 2 (David).