Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding highest value from sub-arrays in MongoDB documents?
To find the highest value from sub-arrays in MongoDB documents, use the aggregation framework with $unwind, $sort, and $limit operators to flatten arrays, sort by the target field, and return the top result.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" },
{ $sort: { "arrayField.valueField": -1 } },
{ $limit: 1 }
]);
Sample Data
db.findHighestValueDemo.insertMany([
{
_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 }
]
}
]);
{ "acknowledged" : true, "insertedIds" : [ 10001, 10002 ] }
Example: Find Highest Math Score
Find the student with the highest math score across all documents ?
db.findHighestValueDemo.aggregate([
{ $project: {"StudentDetails.StudentName": 1, "StudentDetails.StudentMathScore": 1} },
{ $unwind: "$StudentDetails" },
{ $sort: {"StudentDetails.StudentMathScore": -1} },
{ $limit: 1 }
]);
{
"_id" : 10001,
"StudentDetails" : {
"StudentName" : "John",
"StudentMathScore" : 98
}
}
How It Works
-
$project? Selects only the required fields from StudentDetails array -
$unwind? Flattens the StudentDetails array, creating separate documents for each student -
$sort? Orders documents by StudentMathScore in descending order (-1) -
$limit? Returns only the first (highest scoring) document
Conclusion
Use aggregation pipeline with $unwind to flatten arrays, $sort to order by value, and $limit to get the highest value. This approach works efficiently across multiple documents and sub-arrays.
Advertisements
