w3resource

Retrieve a Random Document in MongoDB Using $sample

How to Retrieve a Random Document from MongoDB?

To retrieve a random document from a MongoDB collection, you can use the aggregation pipeline with the $sample stage. The $sample stage allows you to select a specified number of random documents from a collection, making it ideal for scenarios where you need a randomized subset or a single random record.

Description:

In MongoDB, you can fetch a random document by using the $sample stage in an aggregation pipeline. The $sample stage randomly selects a specified number of documents from the collection, providing an efficient and easy way to retrieve a random record. This approach is particularly useful for sampling data, showing a random item, or testing purposes.

Syntax:

To get a random record from a MongoDB collection, use the following syntax:

db.<collection>.aggregate([
  { $sample: { size: 1 } }
])

Explanation:

  • <collection>: The collection from which you want to retrieve a random document.
  • size: The number of random documents you want to return. Set size to 1 to retrieve a single random document.

Example:

Suppose you have a products collection and want to fetch a single random product document:

Code:

// Use the aggregation pipeline to retrieve one random document from the products collection
db.products.aggregate([
  { $sample: { size: 1 } } // Select a single random document
])

Explanation:

  • db.products.aggregate(...)
    This command initiates an aggregation pipeline on the products collection, which allows for advanced data processing and transformations.
  • { $sample: { size: 1 } }
    The $sample stage is used to retrieve random documents. The size parameter is set to 1, indicating that we want one random document. Increasing size will fetch more random documents as a sample from the collection.

The aggregation pipeline processes this query and returns a randomly selected document from the products collection. This approach is efficient because $sample is optimized for random selection, making it suitable for large collections as well.

Additional Options:

If you need more than one random document, simply adjust the size parameter. For example, setting { size: 5 } will retrieve five random documents.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/mongodb/snippets/how-to-retrieve-a-random-document-from-mongodb.php