How to use $rand Operator In MongoDB

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.

Examplw 1:

db.empInformation.aggregate([{ $match: { $expr: { $gte: [ { $rand: {} }, 0.5 ] } } }, { $sample: { size: 1 } }]);

Output:

Explanation: In the above query we have uses MongoDB aggregation pipeline stage like $match and $expr to filter documents based on a random number generated by $rand and selecting documents where the random number is greater than or equal to 0.5.

Example 2:

db.empInformation.aggregate([{ $match: { $expr: { $gte: [ { $rand: {} }, 0.5 ] } } }, { $sample: { size: 3 } }]);

Output:

Explanation: In the above query we have uses the $match and $expr to filter documents based on a random number generated by $rand and selecting documents where the random number is greater than or equal to 0.5. The $sample is used to retrieve three random documents from the filtered set.

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