1

I am new to MongoDb. I was trying to retreive data from the db. Here is part of my code:

    dbc(TABLENAME).find ( MongoDBObject (UID -> uid)).toList.foreach {s =>
      val Rollno = s.getAs[String](ROLL).getOrElse ("?")

Apparently ROLL is set as integer, and I keep on getting the error java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String Is there an easy solution to get it?

1 Answer 1

4

How about getting it as an integer and then using toString?

dbc(TABLENAME).find ( MongoDBObject (UID -> uid)).toList.foreach {s =>
  val Rollno = s.getAs[Int](ROLL).map(_.toString).getOrElse("?")
Sign up to request clarification or add additional context in comments.

2 Comments

+1 or maybe as an Object, in case it can be either Integer or String (but only if that is possible, otherwise no need to get overly lax).
Also, I would postpone this getOrElse as long as possible. I assume that you replace None by "?" in order to print/output the value somewhere. However, if you have conditionals that depend on the Rollno and that are located between the point where you retrieve the object and where you output it, then it is much cleaner if you can match against Some/Noneinstead of some string/"?". Especially if "?" could actually be a valid result, for example, if you retrieve a a field which could contain arbitrary user input - thus also "?" - but it could also not exist.

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.