Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB/Java: Type safety in DBObjects

I have a field in a MongoDB document that stores an arbitrarily-large number. When I retrieve it as a DBObject (Java driver for MongoDB), I sometimes run into a ClassCastException:

DBObject obj = collection.findOne();
long val = (Long)(o.get("numericVal"));

If the value stored in numericVal is, say, 1234567890, the cast to Long succeeds. If it is, say, 12345, DBObject.get() returns a Double, and the cast fails.

How can I ensure type safety when deserializing MongoDB DBObjects?

like image 599
ericsoco Avatar asked Sep 06 '12 17:09

ericsoco


2 Answers

I think you can avoid the ClassCastException by using the type safe getLong( String key ) rather than cast (Long) and hope that autoboxing does the right thing to get you down to little 'l' long.

http://api.mongodb.org/java/2.8.0/org/bson/BasicBSONObject.html#getLong(java.lang.String)

DBObject obj = collection.findOne();
long val = o.getLong("numericVal");

I too am skeptical of the 12345 becoming Double. There is something else going on here.

like image 64
Bob Kuhar Avatar answered Oct 05 '22 13:10

Bob Kuhar


In general I noticed that numeric values are inserted as double using the shell (or sometimes using other languages)

So for example :

db.dummycollection.update({"mykey" : 100}, { $set : { "millisecage" : 30000000 }})

inserts a double value (30000000.0) but

db.dummycollection.update({"mykey" : 100}, { $set : { "millisecage" : NumberLong(30000000) }})

inserts the correct value in the collection

So if you are in doubt avoid this kind of casting or you can do something like :

Long myValue = ((Number) obj.get("yourkey")).longValue();
like image 41
user2894341 Avatar answered Oct 05 '22 12:10

user2894341