Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding highest value from sub-arrays in MongoDB documents?
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
}
}Advertisements