【问题标题】:MongoDB Aggregation Framework - How To Query For An AverageMongoDB 聚合框架 - 如何查询平均值
【发布时间】:2014-03-30 20:38:04
【问题描述】:

如何使用聚合框架重写此 MongoDB 查询,以在提供的 date 范围之间返回以下模型的平均 price

型号

var PriceSchema = new Schema({
    price: {
        type: Number,
        required: true
    },
    date: {
        type: Date,
        required: true
    }
};

查询

exports.getPriceAverage = function(req, res, next) {
    var start       = moment.utc('03-01-2012').startOf('day');
    var end         = moment.utc('03-01-2012').endOf('month')

    // Aggregation Framework Query Here...
    Price.find({ date: { $lt: end, $gt: start }}, function(err, priceAverage) {
         // Return average price...
    });
};

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    您提到使用聚合,但您使用的是find 函数,该函数会将所有结果返回给客户端。

    相反,您需要将aggregate$avg 一起使用:

    Price.aggregate([
        { $match: { date: { $lt: end, $gt: start } } },
        { $group: { _id: null, avgPrice: { $avg: '$price' } } }
    
    ], function(err, results){
       // process the results (an array of JavaScript objects)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-27
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 2015-11-19
      • 2023-01-31
      • 2014-05-11
      相关资源
      最近更新 更多