justkevin
justkevin

Reputation: 3199

Simplest way to retrieve an int from a mongo result?

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?

Upvotes: 9

Views: 6719

Answers (3)

Rob Moore
Rob Moore

Reputation: 3383

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

Upvotes: 17

user
user

Reputation: 3088

Also, you can do it this way:

int autostart = Integer.valueOf(mapObj.get("autostart").toString());

Regarding your last comment:

If you want double, use this:

int autostart = Double.valueOf(mapObj.get("autostart").toString());

But what is the sense in that? You could rather have :

double autostart = Double.valueOf(mapObj.get("autostart").toString());

Upvotes: 5

poitroae
poitroae

Reputation: 21367

Yep, you only need one cast.

double autostart = (Double) mapObj.get("autostart");

Upvotes: 2

Related Questions