Syntax error MongoDB query to get minimum and maximum value from documents including some duplicate records

MongoDB query to get minimum and maximum value from documents including some duplicate records



For this, use aggregate() and $group. To get minimum and maximum value, use $min and $max.

Let us create a collection with documents −

> db.demo167.insertOne({"Score":60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3693a79e4f06af551997d1")
}
> db.demo167.insertOne({"Score":80});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3693ab9e4f06af551997d2")
}
> db.demo167.insertOne({"Score":60});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3693ad9e4f06af551997d3")
}
> db.demo167.insertOne({"Score":90});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3693b09e4f06af551997d4")
}
> db.demo167.insertOne({"Score":89});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3693b69e4f06af551997d5")
}

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

> db.demo167.find();

This will produce the following output −

{ "_id" : ObjectId("5e3693a79e4f06af551997d1"), "Score" : 60 }
{ "_id" : ObjectId("5e3693ab9e4f06af551997d2"), "Score" : 80 }
{ "_id" : ObjectId("5e3693ad9e4f06af551997d3"), "Score" : 60 }
{ "_id" : ObjectId("5e3693b09e4f06af551997d4"), "Score" : 90 }
{ "_id" : ObjectId("5e3693b69e4f06af551997d5"), "Score" : 89 }

Following is the query to get minimum and maximum value −

> var d = [
...    {
...       "$group": {
...          "_id": "id",
...          "MinimumValue": { "$min": "$Score" },
...          "MaximumValue": { "$max": "$Score" }
...       }
...    }
... ]
> db.demo167.aggregate(d);

This will produce the following output −

{ "_id" : "id", "MinimumValue" : 60, "MaximumValue" : 90 }
Updated on: 2020-04-01T12:00:28+05:30

345 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements