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 throw a ClassCastException:

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

If the value stored in numericValis, say, 1234567890, casting to Long continues. If this is, say, 12345, DBObject.get () returns Double, and casting fails.

How can I ensure type safety when deserializing MongoDB DBObjects files?

+5
source share
2 answers

, ClassCastException, getLong (String key), cast (Long), , autoboxing , "l".

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");

12345, . - .

+5

, , , ( )

, :

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

(30000000.0)

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

, , - :

Long myValue = ((Number) obj.get("yourkey")).longValue();
+4

All Articles