Question

How should I work with Money with MongoID? Should I configure it as BigDecimal? And at rails level? For ActiveRecord we have something called Money, but AFAIK it just supports AR

Was it helpful?

Solution

MongoDB stores numbers in various BSON data types (int, long int, double). I recommend you store money as cents (if U.S. currency) and use the long int datatype.

OTHER TIPS

I ran into this also. Unfortunately BigDecimal stores in Mongodb as a string, so it won't let you sum, sort, etc on it like a float or int.

Integer seem to be the way to go storing the value in cents, possibly using the Money gem to abstract it a bit: https://github.com/RubyMoney/money

Mongo stores the int using 64 bits on most modern machines I think so there is not much risk of needing a larger amount even in cents. It looks like you can store between −9,223,372,036,854,775,808 and 9,223,372,036,854,775,807 cents, so take off two decimal places to get your min/max value in dollars.

http://en.wikipedia.org/wiki/Integer_(computer_science)

If you like the money gem you can store it as a Money type.

An example: https://gist.github.com/michaelkoper/5007636

It stores the money as an array [cents, currency]

class Product
   include Mongoid::Document

  field :price,    type: Money
end

product = Product.new(:price => Money.new(1000, 'EUR'))
product.price.format
# => "€10.00"

I recommend you try money-rails as an alternative. https://github.com/RubyMoney/money-rails It is pretty well maintained and works with mongoid too!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top