简体   繁体   中英

How to get integer value from mongodb bson document using java?

I am trying to retrieve an integer from bson document using the following code:

MongoCursor<Document> cursor = collection.find().iterator();
while (cursor.hasNext()) {
    Document rowDoc = cursor.next();
    int myNum = rowDoc.getInteger("number");
}

then I got this exception:

java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Integer

As I thought number is double my change was:

double myNum = rowDoc.getDouble("number");

But this time I got:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

I've checked the value type in mongo shell returning number . So what am I doing wrong?

尝试int myNum = rowDoc.getInteger("number").getValue();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM