
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Two Random Documents in a MongoDB Collection
Let us first create a collection and add some documents to it
> db.twoRandomDocumentDemo.insertOne({"StudentId":10}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9aad628fa4220163b87") } > db.twoRandomDocumentDemo.insertOne({"StudentId":100}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9add628fa4220163b88") } > db.twoRandomDocumentDemo.insertOne({"StudentId":45}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9b0d628fa4220163b89") } > db.twoRandomDocumentDemo.insertOne({"StudentId":55}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9b3d628fa4220163b8a") } > db.twoRandomDocumentDemo.insertOne({"StudentId":5}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9b7d628fa4220163b8b") } > db.twoRandomDocumentDemo.insertOne({"StudentId":7}); { "acknowledged" : true, "insertedId" : ObjectId("5c9ec9bad628fa4220163b8c") }
Following is the query to display all documents from a collection with the help of find() method
> db.twoRandomDocumentDemo.find();
This will produce the following output
{ "_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 }
Following is the query to get 2 random documents out of 6. Set the size as 2 since we want only 2 documents.
> db.twoRandomDocumentDemo.aggregate([{$sample: {size: 2}}]);
This will produce the following output
{ "_id" : ObjectId("5c9ec9b3d628fa4220163b8a"), "StudentId" : 55 } { "_id" : ObjectId("5c9ec9aad628fa4220163b87"), "StudentId" : 10 }
Here is the second case when you run the above query once again to get different documents
> db.twoRandomDocumentDemo.aggregate([{$sample: {size: 2}}]);
This will produce the following output
{ "_id" : ObjectId("5c9ec9add628fa4220163b88"), "StudentId" : 100 } { "_id" : ObjectId("5c9ec9b7d628fa4220163b8b"), "StudentId" : 5 }
Advertisements