Finding highest value from sub-arrays in MongoDB documents?

MongoDBDatabaseBig Data Analytics

To find the highest value from sub-arrays in documents, you can use an aggregate framework. Let us first create a collection with documents

> db.findHighestValueDemo.insertOne(
   ... {
      ... _id: 10001,
      ... "StudentDetails": [
         ... { "StudentName": "Chris", "StudentMathScore": 56},
         ... { "StudentName": "Robert", "StudentMathScore":47 },
         ... { "StudentName": "John", "StudentMathScore": 98 }]
   ... }
... );
{ "acknowledged" : true, "insertedId" : 10001 }
> db.findHighestValueDemo.insertOne(
   ... {
      ... _id: 10002,
      ... "StudentDetails": [
         ... { "StudentName": "Ramit", "StudentMathScore": 89},
         ... { "StudentName": "David", "StudentMathScore":76 },
         ... { "StudentName": "Bob", "StudentMathScore": 97 }
      ... ]
   ... }
... );
{ "acknowledged" : true, "insertedId" : 10002 }

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

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

This will produce the following output

{
   "_id" : 10001,
   "StudentDetails" : [
      {
         "StudentName" : "Chris",
         "StudentMathScore" : 56
      },
      {
         "StudentName" : "Robert",
         "StudentMathScore" : 47
      },
      {
         "StudentName" : "John",
         "StudentMathScore" : 98
      }
   ]
}
{
   "_id" : 10002,
   "StudentDetails" : [
      {
         "StudentName" : "Ramit",
         "StudentMathScore" : 89
      },
      {
         "StudentName" : "David",
         "StudentMathScore" : 76
      },
      {
         "StudentName" : "Bob",
         "StudentMathScore" : 97
      }
   ]
}

Following is the query to find the highest value from sub-arrays in documents

> db.findHighestValueDemo.aggregate([
   ... {$project:{"StudentDetails.StudentName":1, "StudentDetails.StudentMathScore":1}},
   ... {$unwind:"$StudentDetails"},
   ... {$sort:{"StudentDetails.StudentMathScore":-1}},
   ... {$limit:1}
... ]).pretty();

This will produce the following output

{
   "_id" : 10001,
   "StudentDetails" : {
      "StudentName" : "John",
      "StudentMathScore" : 98
   }
}
raja
Published on 15-Apr-2019 07:45:46
Advertisements