Skip to content

Instantly share code, notes, and snippets.

@digicyc
Created November 30, 2011 23:45
Show Gist options
  • Save digicyc/1411967 to your computer and use it in GitHub Desktop.
Save digicyc/1411967 to your computer and use it in GitHub Desktop.
Casbah
import com.mongodb.casbah.Imports._
class CasbahPlay {
private val mongoConn = MongoConnection()
private val coll = mongoConn("mongotalk")("unicorns")
def getWeight(name: String) = {
val unicorn = (coll.findOne(MongoDBObject("name" -> name)).get
// This is returning Option[Int] = Some(450.0)
// Which causes a ClassCastException
unicorn.getAs[Int]("weight")
}
}
class MyMain extends App {
val casbahPlay = new CasbahPlay
val weight = casbahPlay.getWeight("Aurora") // Exception!
}
db.unicorns.insert({name: 'Aurora', dob: new Date(1991, 0, 24, 13, 0), loves:['carrot', 'grape'], weight: 450, gender: 'f', vampires: 43});
@digicyc
Copy link
Author

digicyc commented Nov 30, 2011

It seems getAs[Int] is returning Option[Int] = Some(450.0) which makes things angered.

getAs[Double] works since Some(450.0) is a double.

@bwmcadams
Copy link

You created the data from the shell. Javascript lacks an integer type - everything is a float.

SOOOOO... By default all your numbers are saved as BSON Double types. Javascript automatically shows Floats w/ no decimal as if they're an int. But the BSON stores them as a double.

scala> m("test")("unicorns")
res0: com.mongodb.casbah.MongoCollection = MongoCollection({ "_id" : { "$oid" : "4ed6c0d774c898556fc56e3e"} , "name" : "Aurora" , "dob" : { "$date" : "1991-01-24T13:00:00Z"} , "loves" : [ "carrot" , "grape"] , "weight" : 450.0 , "gender" : "f" , "vampires" : 43.0})

MongoDB's shell comes with a few built-in type constructors including NumberInt which can be used to explicitly create a BSON Integer:

  db.unicorns.insert({name: 'Aurora', dob: new Date(1991, 0, 24, 13, 0), loves:['carrot', 'grape'], weight: NumberInt(450), gender: 'f', vampires: NumberInt(43)});

Renders now as:

 scala> m("test")("unicorns")
 res0: com.mongodb.casbah.MongoCollection = MongoCollection({ "_id" : { "$oid" : "4ed6c1c4f201dff59ce8245c"} , "name" : "Aurora" , "dob" : { "$date" : "1991-01-24T13:00:00Z"} , "loves" : [ "carrot" , "grape"] , "weight" : 450 , "gender" : "f" , "vampires" : 43})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment