Getting the highest value of a column in MongoDB?


To get the highest value of a column in MongoDB, you can use sort() along with limit(1). The syntax is as follows −

db.yourCollectionName.find().sort({"yourFieldName":-1}).limit(1);

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.gettingHighestValueDemo.insertOne({"Value":1029});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900b885705caea966c5574")
}
> db.gettingHighestValueDemo.insertOne({"Value":3029});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900b8d5705caea966c5575")
}
> db.gettingHighestValueDemo.insertOne({"Value":1092});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900b925705caea966c5576")
}
> db.gettingHighestValueDemo.insertOne({"Value":18484});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900b955705caea966c5577")
}
> db.gettingHighestValueDemo.insertOne({"Value":37474});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900b9c5705caea966c5578")
}
> db.gettingHighestValueDemo.insertOne({"Value":88474});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900ba75705caea966c5579")
}
> db.gettingHighestValueDemo.insertOne({"Value":1938474});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c900bab5705caea966c557a")
}

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

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

The following is the output −

{ "_id" : ObjectId("5c900b885705caea966c5574"), "Value" : 1029 }
{ "_id" : ObjectId("5c900b8d5705caea966c5575"), "Value" : 3029 }
{ "_id" : ObjectId("5c900b925705caea966c5576"), "Value" : 1092 }
{ "_id" : ObjectId("5c900b955705caea966c5577"), "Value" : 18484 }
{ "_id" : ObjectId("5c900b9c5705caea966c5578"), "Value" : 37474 }
{ "_id" : ObjectId("5c900ba75705caea966c5579"), "Value" : 88474 }
{ "_id" : ObjectId("5c900bab5705caea966c557a"), "Value" : 1938474 }

Here is the query to get the highest value of a column in MongoDB −

> db.gettingHighestValueDemo.find().sort({"Value":-1}).limit(1);

The following is the output displaying the highest value −

{ "_id" : ObjectId("5c900bab5705caea966c557a"), "Value" : 1938474 }

Updated on: 30-Jul-2019

805 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements