Min and max values of an array in MongoDB?


To get the min and max values, use $min and $max. Let us create a collection with documents −

> db.demo286.insertOne({"details":[{Value1:70,Value2:50},{Value1:30,Value2:36}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4ac743f49383b52759cbbc")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e4ac743f49383b52759cbbc"),
   "details" : [
      {
         "Value1" : 70,
         "Value2" : 50
      },
      {
         "Value1" : 30,
         "Value2" : 36
      }
   ]
}

Here is the query to get min and max values of an array −

> db.demo286.aggregate([   { "$project": { "name": 1, "MinValue1": { "$min": "$details.Value1" },     "MaxValue2": { "$max": "$details.Value2" } }} ])

This will produce the following output −

{ "_id" : ObjectId("5e4ac743f49383b52759cbbc"), "MinValue1" : 30, "MaxValue2" : 50 }

Updated on: 31-Mar-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements