0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Find Random Document

Use the aggregation pipeline with { $sample: { size: 1 } } to find a random document in MongoDB, like db.collection.aggregate([{ $sample: { size: 1 } }]).
📋

Examples

InputCollection with documents: [{_id:1, name:'A'}, {_id:2, name:'B'}, {_id:3, name:'C'}]
OutputOne random document, e.g., {_id:2, name:'B'}
InputEmpty collection
OutputNo documents returned
InputCollection with one document: [{_id:1, name:'OnlyOne'}]
OutputThe single document {_id:1, name:'OnlyOne'}
🧠

How to Think About It

To get a random document, you ask MongoDB to pick one document at random from the collection. MongoDB's aggregation framework has a special stage called $sample that does exactly this by randomly selecting the specified number of documents.
📐

Algorithm

1
Start with the collection you want to query.
2
Use the aggregation pipeline to apply the <code>$sample</code> stage.
3
Set the <code>size</code> parameter to 1 to get one random document.
4
Run the aggregation and return the result.
💻

Code

mongodb
db.collection.aggregate([{ $sample: { size: 1 } }]).forEach(doc => printjson(doc))
Output
{ "_id" : ObjectId("..."), "field1" : "value1", "field2" : "value2" }
🔍

Dry Run

Let's trace a collection with three documents through the $sample aggregation.

1

Input collection

[{_id:1, name:'A'}, {_id:2, name:'B'}, {_id:3, name:'C'}]

2

Apply $sample with size 1

Randomly pick one document from the three

3

Output

Returns one document, e.g., {_id:2, name:'B'}

StepActionResult
1Input collection[{_id:1, name:'A'}, {_id:2, name:'B'}, {_id:3, name:'C'}]
2Apply $sample size 1Randomly select one document
3Output{_id:2, name:'B'}
💡

Why This Works

Step 1: Use aggregation pipeline

MongoDB's aggregation framework lets you process data step-by-step using stages.

Step 2: Use $sample stage

$sample randomly selects documents from the collection, making it easy to get random results.

Step 3: Set size to 1

Setting size: 1 tells MongoDB to return exactly one random document.

🔄

Alternative Approaches

Using count and skip
mongodb
const count = db.collection.countDocuments();
const randomIndex = Math.floor(Math.random() * count);
db.collection.find().skip(randomIndex).limit(1).forEach(doc => printjson(doc));
This method works but is less efficient on large collections because it requires counting and skipping documents.
Using $sample with larger size
mongodb
db.collection.aggregate([{ $sample: { size: 5 } }])
You can get multiple random documents by increasing the size, but it uses more resources.

Complexity: O(k) time, O(k) space

Time Complexity

The $sample stage efficiently selects k random documents without scanning the entire collection, so time depends mostly on k, the sample size.

Space Complexity

Memory usage is proportional to the number of documents sampled (k), as only those are held in memory.

Which Approach is Fastest?

$sample is faster and more efficient than counting and skipping, especially for large collections.

ApproachTimeSpaceBest For
$sample aggregationO(k)O(k)Efficient random sampling
count + skip + findO(n)O(1)Small collections or legacy support
$sample with larger sizeO(k)O(k)Multiple random documents
💡
Use $sample in aggregation for the simplest and most efficient way to get random documents.
⚠️
Trying to use find() with random sorting or skipping without counting can lead to errors or poor performance.