5

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

Josh
  • 10,961
  • 11
  • 65
  • 108
VP.
  • 5,122
  • 6
  • 46
  • 71
  • like decimal, int, floats ... – sdot257 Sep 28 '10 at 15:53
  • dm is right. Never use floating point numbers to represent money (like floats, doubles). This will make a lot of butthurt. You will lose cents during representation. For example 10.2 may be represented like 10.19999(9). During rounding and different arithmetic operations you will get increasing error. [Why not to use double to represent currency](http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency/3730040#3730040) – Dao Apr 13 '11 at 18:43

4 Answers4

8

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)

Brian Armstrong
  • 19,707
  • 17
  • 115
  • 144
3

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.

dm.
  • 1,982
  • 12
  • 7
2

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"
Michael Koper
  • 9,586
  • 7
  • 45
  • 59
0

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!

P Pramod Nair
  • 171
  • 2
  • 4
  • I have an issue with it. I'm currently using: money-rails v1.12 rails v6 mongoid v7 I would like to set the default currency to be used by each model instance. I have set the field in my model like below `field :price, type: Money, with_model_currency: :currency` But when I try to create or fetch records I get this error `Mongoid::Errors::InvalidFieldOption` `message: Invalid option :with_model_currency provided for field :price.` How do I use the `with_model_currency` option in a rails mongoid application? How else can I handle money in a rails mongoid application? – Jatto_abdul Apr 29 '20 at 21:36