[SERVER-31594] Add a weighted average aggregation function Created: 17/Oct/17  Updated: 06/Dec/22

Status: Backlog
Project: Core Server
Component/s: Aggregation Framework
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Randar Puust Assignee: Backlog - Query Optimization
Resolution: Unresolved Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Assigned Teams:
Query Optimization
Participants:

 Description   

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



 Comments   
Comment by Mark Agarunov [ 17/Oct/17 ]

Hello randar,

Thank you for the detailed example. I've set the fixVersion to "Needs Triage" for this new feature to be scheduled against our currently planned work. Updates will be posted on this ticket as they happen.

Thanks,
Mark

Generated at Thu Feb 08 04:27:34 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.