SharifS
SharifS

Reputation: 90

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?

Upvotes: 2

Views: 2828

Answers (1)

Vaibhav
Vaibhav

Reputation: 46

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

Upvotes: 3

Related Questions