MongoDB: Get a Random Document from a Collection

Last updated on September 12, 2021 Guest Contributor Loading... Post a comment

This short and straight-to-the-point post shows you how to randomly retrieve single or multiple documents from a collection in your MongoDB database by using the $sample aggregation.

1. To get a random document:

db.collectionName.aggregate([{ $sample: { size: 1 } }])

If you want to select multiple documents, then set size to an integer greater than 1. Note that in this case, $sample may output the same document more than once in its result set.

2. To get a random document that matches some conditions, use:

db.collectionName.aggregate([
    { $match: { /* some conditions here */ } },
    { $sample: { size: 1 } }
])

For example, the following aggregation operation randomly selects a user with an age is more than 18:

db.users.aggregate([
    { 
      $match: { 
        age: {$gte: 18} 
      }
    },
    { $sample: { size: 1 } }
])

You can set size to a bigger integer to gain more documents.

Reference: https://docs.mongodb.com/manual/reference/operator/aggregation/sample/

Further reading:

Happy coding.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like