Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-31594

Add a weighted average aggregation function

    • Type: Icon: New Feature New Feature
    • Resolution: Unresolved
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Aggregation Framework
    • Labels:
      None
    • Query Optimization

      Although it's possible to aggregate data and use a weighted average (https://support.microsoft.com/en-ca/help/214049/how-to-calculate-weighted-averages-in-excel), it is very cumbersome requiring a nested set of group and projection aggregates. See https://stackoverflow.com/questions/46739027/using-weighted-average-with-mongodb-and-group.

      I would like to see a weighted average accumulator function along with $avg. e.g.

      db.sales.aggregate(
         [
            {
              $group : {
                 _id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" } },
                 totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },
                 averageQuantity: { $weighted_avg: { $value : "$quantity", $weight: "$weight" },
                 count: { $sum: 1 }
              }
            }
         ]
      )
      

            Assignee:
            backlog-query-optimization [DO NOT USE] Backlog - Query Optimization
            Reporter:
            randar Randar Puust
            Votes:
            1 Vote for this issue
            Watchers:
            6 Start watching this issue

              Created:
              Updated: