user2663619
user2663619

Reputation: 1

Return the largest value for each type within the same query

I have a schema for lifts which hold two key pieces of information - lift (bench, deadlift, squat, etc) as well as weight (for the weight lifted).

What I would like to know is how do I go about finding the largest weight lifted for each lift.

I can populate an array with lifts for a given user, but do not know how to further reduce the results down, can this be done in the same query?

var lift = new schema({
    uID: { type: String },
    lift: { type: String },
    weight: { type: Number },
    measurement: { type: String },
    date: { type: Date, default: Date.now },
    gear: [{type: String}]
});

I am using Mongoose with Node.js and Express.

Upvotes: 0

Views: 45

Answers (1)

Derick
Derick

Reputation: 36784

Something like this will do (on the MongoDB shell with the aggregation framework):

db.so.aggregate( [
    { $group: {
        _id: '$lift',
        max: { $max: '$weight' }
    } }
] );

With the following input (abridged):

db.so.insert( { lift: 'bench', weight: 80 } );
db.so.insert( { lift: 'bench', weight: 40 } );
db.so.insert( { lift: 'bench', weight: 76 } );
db.so.insert( { lift: 'squat', weight: 76 } );
db.so.insert( { lift: 'squat', weight: 72 } );
db.so.insert( { lift: 'squat', weight: 172 } );
db.so.insert( { lift: 'deadlift', weight: 142 } );

This outputs:

{
    "result" : [
        {
            "_id" : "deadlift",
            "max" : 142
        },
        {
            "_id" : "squat",
            "max" : 172
        },
        {
            "_id" : "bench",
            "max" : 80
        }
    ],
    "ok" : 1
}

In node.js, you'd change:

db.so.aggregate( [
    { $group: {
        _id: '$lift',
        max: { $max: '$weight' }
    } }
] );

with:

collection.aggregate( [
    { $group: {
        _id: '$lift',
        max: { $max: '$weight' }
    } }
], function(err, result) {

} );

Upvotes: 1

Related Questions