sum to FluentI'd like to be able to access the database function sum, but we can do with count today.
I've run into a use case where I want to return the total number of items, and their total cost. I can use count, but am having to run raw sql in order to retrieve the sum of their cost.
I propose that sum be added, similar to how count is implemented, but sum would take the name of the column to sum.
Assume a ShoppingCart model with Item model children.
let numberOfItems = shoppingCart.items.count()
let totalCost = shoppingCart.items.sum("price")
This change would allow me to remove the raw sql code in my controllers, running raw sql also requires me to add the Droplet to the controllers just for this one part, so I could remove that requirement too.
This seems like the right solution as it matches a paradigm already laid out by count.
I think this is a good idea, and shouldn't stop at SUM. The AVG, MIN and MAX aggregate functions are also universally supported and behave exactly the same.
On a second thought, implementing either on Mongo will require tapping into the aggregation pipeline, but possible nevertheless.
Most helpful comment
I think this is a good idea, and shouldn't stop at
SUM. TheAVG,MINandMAXaggregate functions are also universally supported and behave exactly the same.