1

I was looking how to save decimals using MongoDB and stumbled across a few ideas.

  1. Save it as String (as I'm using Java Spring Framework, this is the default implementation)

    value: "3.44"

  2. Save it the ebay way using a nested document with the unscaled value + scale: http://www.technology-ebay.de/the-teams/mobile-de/blog/mapping-bigdecimals-with-morphia-for-mongodb.html

    value: { unscaled: NumberLong(344) , scale: 2 }

  3. Save the digits before and behind the decimal point separately

    value: { major: 3 , minor: 44 }

Basically I'd say:

  1. Is useless, because I can't sort it as numbers (i.e. "9" > "12")

  2. If ebay uses this, it can't be that bad. But I can't figure out how to sort those values?!

  3. Sort is pretty easy: db.collection.find().sort({"value.major":1, "value.minor":1})

Questions:

How do you implement it?

How does sorting work using approach 2.?

Thank you!

Workarounds:

  1. Store major as integer and minor as string:

    value: { major: 3 , minor: "44" }

  2. Define the max. precision of your decimal and then you can fill the minor value with zeros. For example with precision = 10:

    value: { major: 3 , minor: 4400000000 }

Benjamin M
  • 23,599
  • 32
  • 121
  • 201
  • possible duplicate of [MongoDB - What about Decimal type of value?](http://stackoverflow.com/questions/11541939/mongodb-what-about-decimal-type-of-value) – JohnnyHK Feb 07 '14 at 20:03
  • In your referenced question the the answer is to use an int, which has a fixed number of digits behind the decimal point. But `this` question is about **sorting** *and* **variable number of digits behind the decimal point**. – Benjamin M Feb 07 '14 at 20:27
  • Your 3rd option doesn't work. Imagine if it were `3.5` being stored. Unless you store the `"minor"` as a string value, `44` is greater than `5`. `"44"` however is less than `"5"`. – WiredPrairie Feb 07 '14 at 21:53
  • The second one isn't sortable in a meaningful way on the database server. It's only useful as a data value. – WiredPrairie Feb 07 '14 at 21:53
  • Dammit, you are right. Any idea how to make it work? – Benjamin M Feb 07 '14 at 22:07
  • As I mentioned, you could do #3 if the `minor` value was stored as a string. Or, wait a few more years for MongoDB to implement the data type properly. :) (https://jira.mongodb.org/browse/SERVER-1393) – WiredPrairie Feb 07 '14 at 22:09
  • Hm, I think I can only wait a few more days, not years. But you're right, when using a String as minor the sorting would work. That's really a badass hacky solution, but it seems to be the only working solution... – Benjamin M Feb 08 '14 at 01:59
  • 1
    An alternative of course would be, to say: My Decimal has a precision of 12, and then fill the `minor` value with `000000` until it's 12 digits long. I.e. `12.44` becomes `major: 12` and `minor: 440000000000`. – Benjamin M Feb 08 '14 at 14:50

0 Answers0