Alex Rivera | Logout

Simplest way to retrieve an int from a mongo result?

Asked 2013-03-04T15:41:02.617
9

I'm pulling an int from a mongo cursor object like so:

DBObject mapObj = cursor.next();
int autostart = (int) (double) (Double) mapObj.get("autostart");

It seems strange that I have to triple cast to get it to an integer, is there a better way?

Edit
Report

1 Answer

17

I think what you are really looking for is something like this:

DBObject mapObj = cursor.next();
int autostart = ((Number) mapObj.get("autostart")).intValue();

No conversion to a string and it is safe if the value gets converted to a Double or Long (with the potential loss of precision) from the original Integer value. Double, Long and Integer all extend Number.

HTH Rob

answered 2013-03-05T04:09:33.133

Your Answer