这样的事情会做(在具有聚合框架的 MongoDB shell 上):
db.so.aggregate( [
{ $group: {
_id: '$lift',
max: { $max: '$weight' }
} }
] );
使用以下输入(删节):
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 } );
这输出:
{
"result" : [
{
"_id" : "deadlift",
"max" : 142
},
{
"_id" : "squat",
"max" : 172
},
{
"_id" : "bench",
"max" : 80
}
],
"ok" : 1
}
在 node.js 中,你会改变:
db.so.aggregate( [
{ $group: {
_id: '$lift',
max: { $max: '$weight' }
} }
] );
和:
collection.aggregate( [
{ $group: {
_id: '$lift',
max: { $max: '$weight' }
} }
], function(err, result) {
} );