MongoDB Query to Find Random Document
{ $sample: { size: 1 } } to find a random document in MongoDB, like db.collection.aggregate([{ $sample: { size: 1 } }]).Examples
How to Think About It
$sample that does exactly this by randomly selecting the specified number of documents.Algorithm
Code
db.collection.aggregate([{ $sample: { size: 1 } }]).forEach(doc => printjson(doc))Dry Run
Let's trace a collection with three documents through the $sample aggregation.
Input collection
[{_id:1, name:'A'}, {_id:2, name:'B'}, {_id:3, name:'C'}]
Apply $sample with size 1
Randomly pick one document from the three
Output
Returns one document, e.g., {_id:2, name:'B'}
| Step | Action | Result |
|---|---|---|
| 1 | Input collection | [{_id:1, name:'A'}, {_id:2, name:'B'}, {_id:3, name:'C'}] |
| 2 | Apply $sample size 1 | Randomly select one document |
| 3 | Output | {_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
const count = db.collection.countDocuments(); const randomIndex = Math.floor(Math.random() * count); db.collection.find().skip(randomIndex).limit(1).forEach(doc => printjson(doc));
db.collection.aggregate([{ $sample: { size: 5 } }])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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| $sample aggregation | O(k) | O(k) | Efficient random sampling |
| count + skip + find | O(n) | O(1) | Small collections or legacy support |
| $sample with larger size | O(k) | O(k) | Multiple random documents |
$sample in aggregation for the simplest and most efficient way to get random documents.find() with random sorting or skipping without counting can lead to errors or poor performance.