Get Random record from MongoDB?

MongoDBDatabaseBig Data Analytics

To get a random record from MongoDB, you can use aggregate function. The syntax is as follows:

db.yourCollectionName.aggregate([{$sample:{size:1}}]);

To understand the above syntax, let us create a collection with some documents. The query to create collection is as follows:

>db.employeeInformation.insert({"EmployeeId":1,"EmployeeName":"Maxwell","EmployeeAge":26});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":2,"EmployeeName":"David","EmployeeAge":25});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":3,"EmployeeName":"Carol","EmployeeAge":24});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":4,"EmployeeName":"Bob","EmployeeAge":28});
WriteResult({ "nInserted" : 1 })
>db.employeeInformation.insert({"EmployeeId":5,"EmployeeName":"Sam","EmployeeAge":27);
WriteResult({ "nInserted" : 1 })

Now you can display all documents from a collection with the help of find() method. The query is as follows:

> db.employeeInformation.find().pretty();

The following is the output:

{
   "_id" : ObjectId("5c6d3079734e98fc0a434ae5"),
   "EmployeeId" : 1,
   "EmployeeName" : "Maxwell",
   "EmployeeAge" : 26
}
{
   "_id" : ObjectId("5c6d308c734e98fc0a434ae6"),
   "EmployeeId" : 2,
   "EmployeeName" : "David",
   "EmployeeAge" : 25
}
{
   "_id" : ObjectId("5c6d309d734e98fc0a434ae7"),
   "EmployeeId" : 3,
   "EmployeeName" : "Carol",
   "EmployeeAge" : 24
}
{
   "_id" : ObjectId("5c6d30ab734e98fc0a434ae8"),
   "EmployeeId" : 4,
   "EmployeeName" : "Bob",
   "EmployeeAge" : 28
}
{
   "_id" : ObjectId("5c6d30bb734e98fc0a434ae9"),
   "EmployeeId" : 5,
   "EmployeeName" : "Sam",
   "EmployeeAge" : 27
}

Here is the query to get random record:

> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();

The following is the output:

{
   "_id" : ObjectId("5c6d30bb734e98fc0a434ae9"),
   "EmployeeId" : 5,
   "EmployeeName" : "Sam",
   "EmployeeAge" : 27
}

Let us get another random record using the same query:

> db.employeeInformation.aggregate([{$sample:{size:1}}]).pretty();

The following is the output:

{
   "_id" : ObjectId("5c6d308c734e98fc0a434ae6"),
   "EmployeeId" : 2,
   "EmployeeName" : "David",
   "EmployeeAge" : 25
}
raja
Published on 18-Mar-2019 11:13:29
Advertisements