To get the maximum marks records, use sort() in descending order along with limit 1. Let us create a collection with documents −
> db.demo241.insertOne({"Marks":67});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e441f729af932883c61ea40")
}
> db.demo241.insertOne({"Marks":89});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e441f769af932883c61ea41")
}
> db.demo241.insertOne({"Marks":78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e441f789af932883c61ea42")
}Display all documents from a collection with the help of find() method −
> db.demo241.find();
This will produce the following output −
{ "_id" : ObjectId("5e441f729af932883c61ea40"), "Marks" : 67 }
{ "_id" : ObjectId("5e441f769af932883c61ea41"), "Marks" : 89 }
{ "_id" : ObjectId("5e441f789af932883c61ea42"), "Marks" : 78 }Following is the query to get the maximum marks −
> db.demo241.find().sort({Marks:-1}).limit(1);This will produce the following output −
{ "_id" : ObjectId("5e441f769af932883c61ea41"), "Marks" : 89 }