How to Select a Random Sample of Documents?

In MongoDB developers often need to retrieve a random record from a collection which can be challenging due to the lack of a method for random record selection. However, MongoDB offers several approaches for How to Select a Random Sample of Documents is discussed below:

  1. Using $sample Operator
  2. Using $rand Operator

Let’s set up an en environment

To understand How to get a random record from MongoDB we need a collection and some documents on which we will perform various operations and queries. Here we will consider a collection called empInformation which contains information like EmployeeId, Employeename, and Employeeage of the Employees in various documents.

Output:

How to Get a Random Record From MongoDB

MongoDB is the most flexible NoSQL documentoriented database system which is very popular for its flexibility and scalability. Almost every time the developer works with MongoDB they need to query the collection and retrieve a random document from it.

In this article, We will learn about How to get a random record from MongoDB by understanding various methods along with the implementation and examples.

Similar Reads

How to Select a Random Sample of Documents?

In MongoDB developers often need to retrieve a random record from a collection which can be challenging due to the lack of a method for random record selection. However, MongoDB offers several approaches for How to Select a Random Sample of Documents is discussed below:...

1. Using $sample Operator

MongoDB’s $sample operator is a powerful tool for retrieving random records from a collection. It allows us to specify the number of random documents we want to retrieve....

1. Using $rand Operator

The $rand operator is another method for retrieving random records from a MongoDB collection. The $rand operator sorts documents randomly based on a given field. This approach is useful when we need to retrieve all documents in a collection in a random order....

Conclusion

Overall, Retrieving a random record from MongoDB can be achieved using various methods, including the $sample operator, the $rand operator in the MongoDB shell. Each method has its advantages and can be used based on the specific requirements of your application.Now you can easily find the random records or document from the collection in MongoDB....

Contact Us