2

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?

6
  • Maybe you have mixed types. Try ((Number)rowDoc.get("number")).intValue() Commented Mar 14, 2017 at 22:33
  • 1
    @shmosel : public <T> T get("number", Number.class) is more appropriate. Commented Mar 14, 2017 at 22:43
  • What you do with your myNum variable? Commented Mar 14, 2017 at 22:44
  • @shmosel: It solved my problem. Thanks a lot. I would still appreciate some detailed explanation. Commented Mar 14, 2017 at 22:49
  • Just a thought. Why are you storing them as double and integer if you just care about int value ? Would it help to update the data to just include integer ? Then int myNum = rowDoc.getInteger("number"); will work as expected. Commented Mar 14, 2017 at 23:00

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.