如何使用聚合框架在mongoDB中计算加权平均值? [英] How do I calculate a weighted average in mongoDB using aggregation framework?

查看:307
本文介绍了如何使用聚合框架在mongoDB中计算加权平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算一组文档的加权平均值。每个文档在单独的字段中都包含权重和值。
这是一个示例:
我有以下两个代表销售交易的文档。

I need to calculate weighted average over a set of documents. Each document contains both a weight and a value in a separate field. Here is an example: I have following 2 documents representing a sales transaction.

{
    quantity : 3,
    price : 2
}

{
    quantity : 9,
    price : 6
}

我想找到两个交易的平均价格。这是加权平均值,其中权重是数量,价值是价格。可以通过

I want to find the average price for both transactions. This is a weighted average where weight is the quantity and value is the price. This can be calculated by

AveragePrice =(3 * 2 + 9 * 6)/(3 + 9)来计算

如何使用聚合框架执行此计算?

How do I perform this calculation using aggregation framework?

推荐答案

为此,您应该首先计算所得比率的分子(加权和)和分母(权重之和)。之后,您只需将它们彼此分开:

To do so you should first calculate numerator (weighted sum) and denominator (sum of weights) of the resulting ratio. After that you'll only need to divide one by another:

db.collection.aggregate({
  $group : {
     _id : 'weighted average', // build any group key ypo need
     numerator: { $sum: { $multiply: [ "$price", "$quantity" ] } },
     denominator: { $sum: "$quantity" }
  }
}, {
  $project: {
    average: { $divide: [ "$numerator", "$denominator" ] }
  }
})

有关更多信息,请参见聚合管道文档

For more info see Aggregation Pipeline documentation.

这篇关于如何使用聚合框架在mongoDB中计算加权平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆