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 Answers1

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("?")
Malte Schwerhoff
  • 12,684
  • 4
  • 41
  • 71
  • +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 09: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``/``None``instead 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 09:26