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?
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With