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
How to match and group array elements with the max value in MongoDB aggregation?
To match and group array elements with the maximum value in MongoDB aggregation, use $filter with $max to find elements with the highest score, then $group to count occurrences by name.
Syntax
db.collection.aggregate([
{
"$project": {
"maxElement": {
"$arrayElemAt": [
{ "$filter": {
"input": "$arrayField",
"cond": { "$eq": ["$$this.score", { "$max": "$arrayField.score" }] }
}},
0
]
}
}
},
{
"$group": {
"_id": "$maxElement.name",
"count": { "$sum": 1 }
}
}
])
Sample Data
db.demo510.insertMany([
{
"details": [
{ "Name": "Chris", "Score": 56 },
{ "Name": "David", "Score": 45 }
]
},
{
"details": [
{ "Name": "Chris", "Score": 56 },
{ "Name": "David", "Score": 47 }
]
},
{
"details": [
{ "Name": "Chris", "Score": 45 },
{ "Name": "David", "Score": 91 }
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e8845fa987b6e0e9d18f582"),
ObjectId("5e8845fb987b6e0e9d18f583"),
ObjectId("5e8845fb987b6e0e9d18f584")
]
}
Example: Find Max Score Elements and Group
db.demo510.aggregate([
{
"$project": {
"details": {
"$arrayElemAt": [
{
"$filter": {
"input": "$details",
"as": "res",
"cond": {
"$eq": [
"$$res.Score",
{
"$max": {
"$map": {
"input": "$details",
"as": "out",
"in": "$$out.Score"
}
}
}
]
}
}
},
0
]
}
}
},
{
"$group": {
"_id": "$details.Name",
"Name": { "$first": "$details.Name" },
"count": { "$sum": 1 }
}
}
]);
{ "_id": "David", "Name": "David", "count": 1 }
{ "_id": "Chris", "Name": "Chris", "count": 2 }
How It Works
-
$mapextracts all Score values from the details array -
$maxfinds the highest score in each document's array -
$filterreturns only elements matching the maximum score -
$arrayElemAtgets the first (and only) matching element -
$groupcounts how many times each name appears with max score
Conclusion
This aggregation pipeline efficiently identifies array elements with maximum values and groups them by name. Chris appears twice with max scores (56, 56) while David appears once with max score (91).
Advertisements
