How to find two random documents in a MongoDB collection of 6?


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 }

Updated on: 30-Jul-2019

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements