Extracting objects from the database
We now have a database populated with a few users. Let's query this database from the REPL:
scala> import com.mongodb.casbah.Imports._ import com.mongodb.casbah.Imports._ scala> val collection = MongoClient()("github")("users") MongoCollection = users scala> val maybeUser = collection.findOne Option[collection.T] = Some({ "_id" : { "$oid" : "562e922546f953739c43df02"} , "github_id" : 1 , "login" : "mojombo" , "repos" : ...
The findOne
method returns a single DBObject
object wrapped in an option, unless the collection is empty, in which case it returns None
. We must therefore use the get
method to extract the object:
scala> val user = maybeUser.get collection.T = { "_id" : { "$oid" : "562e922546f953739c43df02"} , "github_id" : 1 , "login" : "mojombo" , "repos" : ...
As you learned earlier in this chapter, DBObject
is a map-like object with keys of type String
and values of type AnyRef
:
scala> user("login") AnyRef = mojombo
In general,...