Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to find two random documents in a MongoDB collection of 6?
To find two random documents from a MongoDB collection, use the $sample aggregation stage. This operator randomly selects a specified number of documents from the collection efficiently.
Syntax
db.collection.aggregate([
{ $sample: { size: NumberOfDocuments } }
]);
Sample Data
Let us create a collection with 6 student documents ?
db.twoRandomDocumentDemo.insertMany([
{"StudentId": 10},
{"StudentId": 100},
{"StudentId": 45},
{"StudentId": 55},
{"StudentId": 5},
{"StudentId": 7}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9ec9aad628fa4220163b87"),
ObjectId("5c9ec9add628fa4220163b88"),
ObjectId("5c9ec9b0d628fa4220163b89"),
ObjectId("5c9ec9b3d628fa4220163b8a"),
ObjectId("5c9ec9b7d628fa4220163b8b"),
ObjectId("5c9ec9bad628fa4220163b8c")
]
}
Following is the query to display all documents from the collection ?
db.twoRandomDocumentDemo.find();
{ "_id": ObjectId("5c9ec9aad628fa4220163b87"), "StudentId": 10 }
{ "_id": ObjectId("5c9ec9add628fa4220163b88"), "StudentId": 100 }
{ "_id": ObjectId("5c9ec9b0d628fa4220163b89"), "StudentId": 45 }
{ "_id": ObjectId("5c9ec9b3d628fa4220163b8a"), "StudentId": 55 }
{ "_id": ObjectId("5c9ec9b7d628fa4220163b8b"), "StudentId": 5 }
{ "_id": ObjectId("5c9ec9bad628fa4220163b8c"), "StudentId": 7 }
Example: Get 2 Random Documents
Set the size as 2 to get exactly 2 random documents from the collection of 6 ?
db.twoRandomDocumentDemo.aggregate([
{ $sample: { size: 2 } }
]);
{ "_id": ObjectId("5c9ec9b3d628fa4220163b8a"), "StudentId": 55 }
{ "_id": ObjectId("5c9ec9aad628fa4220163b87"), "StudentId": 10 }
Running the Query Again
Each execution returns different random documents ?
db.twoRandomDocumentDemo.aggregate([
{ $sample: { size: 2 } }
]);
{ "_id": ObjectId("5c9ec9add628fa4220163b88"), "StudentId": 100 }
{ "_id": ObjectId("5c9ec9b7d628fa4220163b8b"), "StudentId": 5 }
Key Points
-
$sampleuses efficient random sampling algorithms for large collections. - The
sizeparameter specifies how many random documents to return. - Each query execution produces different random results.
Conclusion
Use $sample in an aggregation pipeline to efficiently select random documents from a collection. This method is optimized for performance and works well with both small and large datasets.
Advertisements
