Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to retrieve an int from a mongo result?

Tags:

java

mongodb

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?

like image 500
justkevin Avatar asked Mar 04 '13 15:03

justkevin


3 Answers

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

like image 58
Rob Moore Avatar answered Nov 09 '22 01:11

Rob Moore


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

like image 20
user Avatar answered Nov 08 '22 23:11

user


Yep, you only need one cast.

double autostart = (Double) mapObj.get("autostart");
like image 2
poitroae Avatar answered Nov 09 '22 01:11

poitroae