MongoDB aggregation to get two documents with the least marks


To get the sorted list of marks, use $sort. Use $limit: 2 to display only two such documents with least marks. Let us create a collection with documents −

> db.demo709.insertOne({Name:"John","Marks":75});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea839005d33e20ed1097b76")
}
> db.demo709.insertOne({Name:"Chris","Marks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea839075d33e20ed1097b77")
}
> db.demo709.insertOne({Name:"David","Marks":54});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea839125d33e20ed1097b78")
}
> db.demo709.insertOne({Name:"Bob","Marks":69});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea839295d33e20ed1097b79")
}

Display all documents from a collection with the help of find() method −

> db.demo709.find();

This will produce the following output −

{ "_id" : ObjectId("5ea839005d33e20ed1097b76"), "Name" : "John", "Marks" : 75 }
{ "_id" : ObjectId("5ea839075d33e20ed1097b77"), "Name" : "Chris", "Marks" : 45 }
{ "_id" : ObjectId("5ea839125d33e20ed1097b78"), "Name" : "David", "Marks" : 54 }
{ "_id" : ObjectId("5ea839295d33e20ed1097b79"), "Name" : "Bob", "Marks" : 69 }

Following is the query to get two documents with least marks −

> db.demo709.aggregate({
...    $group: {
...       _id: '$Marks',
...       ListOfName: { $push: '$Name' }
...    }
... }, {
...    $sort: {
...       '_id': 1
...    }
... }, {
...    $limit: 2
... });

This will produce the following output −

{ "_id" : 45, "ListOfName" : [ "Chris" ] }
{ "_id" : 54, "ListOfName" : [ "David" ] }

Updated on: 14-May-2020

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements