Find minimum value with MongoDB?


To get the minimum value, use sort() along with limit(1). Let us first create a collection with documents −

> db.findMinimumValueDemo.insertOne({"Value":1004});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdfd61abf3115999ed51208")
}
> db.findMinimumValueDemo.insertOne({"Value":983});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdfd61ebf3115999ed51209")
}
> db.findMinimumValueDemo.insertOne({"Value":990});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdfd622bf3115999ed5120a")
}
> db.findMinimumValueDemo.insertOne({"Value":1093});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdfd626bf3115999ed5120b")
}
> db.findMinimumValueDemo.insertOne({"Value":10090});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdfd62fbf3115999ed5120c")
}

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

> db.findMinimumValueDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cdfd61abf3115999ed51208"), "Value" : 1004 }
{ "_id" : ObjectId("5cdfd61ebf3115999ed51209"), "Value" : 983 }
{ "_id" : ObjectId("5cdfd622bf3115999ed5120a"), "Value" : 990 }
{ "_id" : ObjectId("5cdfd626bf3115999ed5120b"), "Value" : 1093 }
{ "_id" : ObjectId("5cdfd62fbf3115999ed5120c"), "Value" : 10090 }

Following is the query to find minimum value −

> db.findMinimumValueDemo.find().sort({Value:1}).limit(1);

This will produce the following output −

{ "_id" : ObjectId("5cdfd61ebf3115999ed51209"), "Value" : 983 }
raja
Published on 14-Jun-2019 14:54:38
Advertisements