I was looking how to save decimals using MongoDB and stumbled across a few ideas.
Save it as String (as I'm using Java Spring Framework, this is the default implementation)
value: "3.44"
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 }
Save the digits before and behind the decimal point separately
value: { major: 3 , minor: 44 }
Basically I'd say:
Is useless, because I can't sort it as numbers (i.e.
"9" > "12"
)If ebay uses this, it can't be that bad. But I can't figure out how to sort those values?!
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:
Store
major
as integer andminor
as string:value: { major: 3 , minor: "44" }
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 }