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?

share|improve this question

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("?")
share|improve this answer
    
+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). – Thilo Jul 15 '12 at 9:18
2  
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. – Malte Schwerhoff Jul 15 '12 at 9:26
    
That worked swell...thank you! – user1510855 Jul 15 '12 at 9:47
1  
@user1510855 Please accept the answer. – cracked_all Jul 15 '12 at 15:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.