【问题标题】:Return the largest value for each type within the same query返回同一查询中每种类型的最大值
【发布时间】:2013-08-08 18:38:30
【问题描述】:

我有一个举重模式,其中包含两个关键信息 - 举重(卧推、硬拉、深蹲等)以及重量(举起的重量)。

我想知道的是如何找到每次提升的最大重量。

我可以为给定用户填充一个带有提升的数组,但不知道如何进一步减少结果,这可以在同一个查询中完成吗?

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}]
});

我将 Mongoose 与 Node.js 和 Express 一起使用。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    这样的事情会做(在带有聚合框架的 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) {
    
    } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2017-05-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多