1

I'm using Money-Rails as field like so:

class Product
  ...
  field :price_GBP, type: Money
  ...
end

And I'm trying to get the average for all price_GBP documents. If the price_GBP field were a float or integer I would something like this:

avg = Product.avg(:price_GBP)

And that would provide me the average price for all products. I've tried:

avg = Product.avg(":price_GBP.cents") #or
avg = Product.avg("price_GBP.fractional")

But neither works. Any ideas?

EDIT:

Here's the price_GBP attribute:

price_GBP: {
    cents: 220,
    currency_iso: "GBP"
},
WagnerMatosUK
  • 4,309
  • 7
  • 56
  • 95
  • Have you looked at how `Money` is stored in the database? Does the documentation say anything? Have you looked at a raw `price_GBP` value without Mongoid in the way? – mu is too short Feb 27 '16 at 18:20
  • Money is a hash (in the Edit above), which is why I thought `Product.avg(":price_GBP.cents")` would do the trick. The Money documentation doesn't say anything and I'm trying to find in the Mongoid docs how to get average on a nested object without having to use the aggregation framework. – WagnerMatosUK Feb 28 '16 at 09:41
  • Try a simple `Model.avg(some_field)` in the console and then look at your Moped logs, you should see an aggregation behind the scenes. Have you tried `Product.avg('price_GBP.cents')` (i.e. no colon inside the string)? If that doesn't work then I guess you're stuck dealing with all the aggregation pipeline ugliness yourself. – mu is too short Feb 28 '16 at 20:14
  • 1
    `Product.avg("price_GBP.fractional")`, there's not `fractional` in your embedded document. Try the [arithmetic functions of the aggregation pipline](https://docs.mongodb.org/manual/reference/operator/aggregation-arithmetic/) to do simple calculations inside mongodb. – Thomas R. Koll Mar 02 '16 at 08:16
  • @ThomasR.Koll do you want to add as an answer so I can mark it as answered? – WagnerMatosUK Mar 31 '16 at 10:01
  • 2
    Nah, i'm happy if your code is workin :) – Thomas R. Koll Mar 31 '16 at 11:48

0 Answers0