簡體   English   中英

如何使用聚合框架在mongoDB中計算加權平均值?

[英]How do I calculate a weighted average in mongoDB using aggregation framework?

我需要計算一組文檔的加權平均值。 每個文檔在單獨的字段中都包含權重和值。 這是一個示例:我有以下2個文檔代表銷售交易。

{
    quantity : 3,
    price : 2
}

{
    quantity : 9,
    price : 6
}

我想找到兩個交易的平均價格。 這是加權平均值,其中權重是數量,價值是價格。 這可以通過

AveragePrice = (3 * 2 + 9 * 6 ) / (3 + 9)

如何使用聚合框架執行此計算?

為此,您應該首先計算所得比率的分子(加權和)和分母(權重之和)。 之后,您只需要彼此分開:

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

有關更多信息,請參見聚合管道文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM