Mongoose provides a way to fetch a random document from a collection using the `aggregate` method and the `$sample` operator.
Here’s an example:
const randomDoc = await MyModel.aggregate([
{ $sample: { size: 1 } }
]);
In this example, we assume you have a Mongoose model called `MyModel` representing your collection.
The `aggregate` method is used to perform aggregation operations on the collection. Within the aggregation pipeline, we use the `$sample` operator to fetch a random document. In this case, we specify `size: 1` to retrieve only one random document.
The result of this aggregation will be an array containing the random document(s) that match the specified criteria. In this example, since we only requested one document, the result will be an array with a single object.
Here’s how you can access the random document:
const randomDocument = randomDoc[0];
Now you can use the `randomDocument` object to access its properties and perform any desired operations.