node.js - Return the largest value for each type within the same query -
i have schema lifts hold 2 key pieces of information - lift (bench, deadlift, squat, etc) weight (for weight lifted).
what know how go finding largest weight lifted each lift.
i can populate array lifts given user, not know how further reduce results down, can done in 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 using mongoose node.js , express.
something (on mongodb shell aggregation framework):
db.so.aggregate( [ { $group: { _id: '$lift', max: { $max: '$weight' } } } ] );
with 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) { } );
Comments
Post a Comment