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 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