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
Get MongoDB documents with max attribute per group in a collection?
To get documents with the maximum attribute per group in a MongoDB collection, use the $sort operator combined with the $group stage in an aggregation pipeline. This approach sorts documents by the grouping field and the target attribute, then uses $first to select the document with the highest value per group.
Sample Data
db.maxAttributePerGroup.insertMany([
{
"StudentFirstName": "John",
"StudentLastName": "Smith",
"StudentAge": 29,
"StudentId": 10
},
{
"StudentFirstName": "Carol",
"StudentLastName": "Taylor",
"StudentAge": 19,
"StudentId": 10
},
{
"StudentFirstName": "Adam",
"StudentLastName": "Smith",
"StudentAge": 34,
"StudentId": 20
},
{
"StudentFirstName": "Bob",
"StudentLastName": "Taylor",
"StudentAge": 58,
"StudentId": 20
}
]);
Display All Documents
db.maxAttributePerGroup.find().pretty();
{
"_id" : ObjectId("5c76ee341e9c5dd6f1f78277"),
"StudentFirstName" : "John",
"StudentLastName" : "Smith",
"StudentAge" : 29,
"StudentId" : 10
}
{
"_id" : ObjectId("5c76ee4e1e9c5dd6f1f78278"),
"StudentFirstName" : "Carol",
"StudentLastName" : "Taylor",
"StudentAge" : 19,
"StudentId" : 10
}
{
"_id" : ObjectId("5c76ee631e9c5dd6f1f78279"),
"StudentFirstName" : "Adam",
"StudentLastName" : "Smith",
"StudentAge" : 34,
"StudentId" : 20
}
{
"_id" : ObjectId("5c76ee791e9c5dd6f1f7827a"),
"StudentFirstName" : "Bob",
"StudentLastName" : "Taylor",
"StudentAge" : 58,
"StudentId" : 20
}
Get Max Attribute Per Group
This query finds the student with the maximum age in each StudentId group ?
db.maxAttributePerGroup.aggregate([
{ "$sort": { "StudentId": 1, "StudentAge": -1 } },
{ "$group": {
"_id": "$StudentId",
"StudentAge": { "$first": "$StudentAge" },
"StudentFirstName": { "$first": "$StudentFirstName" },
"StudentLastName": { "$first": "$StudentLastName" }
}}
]);
{
"_id" : 20,
"StudentAge" : 58,
"StudentFirstName" : "Bob",
"StudentLastName" : "Taylor"
}
{
"_id" : 10,
"StudentAge" : 29,
"StudentFirstName" : "John",
"StudentLastName" : "Smith"
}
How It Works
- $sort: Orders documents by StudentId (ascending) and StudentAge (descending)
-
$group: Groups by StudentId and uses
$firstto select the document with the highest age - $first: Returns the first document in each group after sorting
Conclusion
Use $sort with descending order on the target attribute, then $group with $first to get documents with maximum attribute values per group. This method efficiently finds the top document in each group without complex comparisons.
Advertisements
