Created
November 30, 2011 23:45
-
-
Save digicyc/1411967 to your computer and use it in GitHub Desktop.
Casbah
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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! | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
db.unicorns.insert({name: 'Aurora', dob: new Date(1991, 0, 24, 13, 0), loves:['carrot', 'grape'], weight: 450, gender: 'f', vampires: 43}); |
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
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.