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)
I too am skeptical of the 12345 becoming Double. There is something else going on here.