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:
- Using $sample Operator
- 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 document–oriented 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.
Contact Us