Get maximum and minimum value in MongoDB?


Use $max and $min operator along with aggregate framework to get the maximum and minimum value. Let us first create a collection with documents −

> db.maxAndMinDemo.insertOne({"Value":98});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd698a357806ebf1256f129")
}
> db.maxAndMinDemo.insertOne({"Value":97});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd698af57806ebf1256f12a")
}
> db.maxAndMinDemo.insertOne({"Value":69});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd698b357806ebf1256f12b")
}
> db.maxAndMinDemo.insertOne({"Value":96});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd698b657806ebf1256f12c")
}
> db.maxAndMinDemo.insertOne({"Value":99});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd698b957806ebf1256f12d")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{ "_id" : ObjectId("5cd698a357806ebf1256f129"), "Value" : 98 }
{ "_id" : ObjectId("5cd698af57806ebf1256f12a"), "Value" : 97 }
{ "_id" : ObjectId("5cd698b357806ebf1256f12b"), "Value" : 69 }
{ "_id" : ObjectId("5cd698b657806ebf1256f12c"), "Value" : 96 }
{ "_id" : ObjectId("5cd698b957806ebf1256f12d"), "Value" : 99 }

Following is the query to max and min in MongoDB −

> db.maxAndMinDemo.aggregate([
   { "$group": {
      "_id": null,
      "MaximumValue": { "$max": "$Value" },
      "MinimumValue": { "$min": "$Value" }
   }}
]);

This will produce the following output −

{ "_id" : null, "MaximumValue" : 99, "MinimumValue" : 69 }

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements