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
Find maximum score for duplicate Name values in MongoDB?
To find the maximum score for duplicate Name values in MongoDB, use the aggregation pipeline with $group and $max operators. This groups documents by name and calculates the highest score for each group.
Syntax
db.collection.aggregate([
{
$group: {
_id: "$fieldName",
maxScore: { $max: "$scoreField" }
}
}
]);
Sample Data
db.demo114.insertMany([
{ "Score": 60, "Name": "Chris" },
{ "Score": 87, "Name": "Chris" },
{ "Score": 45, "Name": "David" },
{ "Score": 67, "Name": "Chris" },
{ "Score": 38, "Name": "David" }
]);
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("..."),
"1": ObjectId("..."),
"2": ObjectId("..."),
"3": ObjectId("..."),
"4": ObjectId("...")
}
}
View Sample Data
db.demo114.find();
{ "_id": ObjectId("..."), "Score": 60, "Name": "Chris" }
{ "_id": ObjectId("..."), "Score": 87, "Name": "Chris" }
{ "_id": ObjectId("..."), "Score": 45, "Name": "David" }
{ "_id": ObjectId("..."), "Score": 67, "Name": "Chris" }
{ "_id": ObjectId("..."), "Score": 38, "Name": "David" }
Find Maximum Score by Name
db.demo114.aggregate([
{
$group: {
_id: "$Name",
maximumScore: { $max: "$Score" }
}
}
]);
[
{ "_id": "Chris", "maximumScore": 87 },
{ "_id": "David", "maximumScore": 45 }
]
Alternative Method: Using group() (Legacy)
The legacy group() method can also be used, though aggregation pipeline is recommended ?
db.demo114.group({
key: { Name: true },
reduce: function(current, previous) {
if (previous.maximumScore < current.Score) {
previous.maximumScore = current.Score;
}
},
initial: { maximumScore: 0 }
});
Key Points
-
$groupgroups documents by the specified field (_id: "$Name"). -
$maxfinds the maximum value within each group efficiently. - Aggregation pipeline is preferred over the legacy
group()method.
Conclusion
Use $group with $max in an aggregation pipeline to find maximum scores for duplicate names. This approach is efficient and follows modern MongoDB best practices.
Advertisements
