Get MongoDB documents with max attribute per group in a collection?



You can get documents with max attribute per group in a collection using $sort operator along with $group statement.

To understand the concept further, let us create a collection with document. The query to create a collection with document is as follows −

> db.maxAttributePerGroup.insertOne({"StudentFirstName":"John","StudentLastName":"Smith    ","StudentAge":29,"StudentId":10}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c76ee341e9c5dd6f1f78277") } > db.maxAttributePerGroup.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylo    r","StudentAge":19,"StudentId":10}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c76ee4e1e9c5dd6f1f78278") } > db.maxAttributePerGroup.insertOne({"StudentFirstName":"Adam","StudentLastName":"Smit    h","StudentAge":34,"StudentId":20}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c76ee631e9c5dd6f1f78279") } > db.maxAttributePerGroup.insertOne({"StudentFirstName":"Bob","StudentLastName":"Taylor"    ,"StudentAge":58,"StudentId":20}); {    "acknowledged" : true,    "insertedId" : ObjectId("5c76ee791e9c5dd6f1f7827a") }

Display all documents from a collection with the help of find() method. The query is as follows −

> db.maxAttributePerGroup.find().pretty();

Output

{    "_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 }

Here is the query to get documents with max attribute per group in a collection −

> db.maxAttributePerGroup.aggregate([    ... {"$sort":{"StudentId":1,"StudentAge":-1}},    ... {$group:{    ... "_id":"$StudentId",    ... "StudentAge":{"$first":"$StudentAge"},    ... "StudentFirstName":{"$first":"$StudentFirstName"},    ... "StudentLastName":{"$first":"$StudentLastName"} ... }} ]).pretty();

Output

{    "_id" : 20,    "StudentAge" : 58,    "StudentFirstName" : "Bob",    "StudentLastName" : "Taylor" } {    "_id" : 10,    "StudentAge" : 29,    "StudentFirstName" : "John",    "StudentLastName" : "Smith" }
Updated on: 2019-07-30T22:30:25+05:30

393 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements