MongoDB – get documents with max attribute per group in a collection

MongoDB aggregation offers the $max operator, but in your case you want the “whole” record as it is. So the appropriate thing to do here is $sort and then use the $first operator within a $group statement:

db.collection.aggregate([
    { "$sort": { "session": 1, "age": -1 } },
    { "$group": {
        "_id": "$session",
        "age": { "$first": "$age" },
        "firstName": { "$first" "$firstName" },
        "lastName": { "$first": "$lastName" }
    }}
])

So the “sorting” gets the order right, and the “grouping” picks the first occurrence within the “grouping” key where those fields exist.

Mostly $first here because the $sort is done in reverse order. You can also use $last when in an ascending order as well.

Leave a Comment