I'm trying to fetch doc and get it's attribute. When I use findOne method, I expect to get MongoDBObject, but I receive Option[com.mongodb.DBObject]. How to get an attribute from it? Is it possible to get MongoDBObject instead of this?
scala> var col = MongoClient()("test")("counters")
col: com.mongodb.casbah.MongoCollection = MongoCollection({ "_id" : "some" , "value" : 0})
scala> var doc = col.findOne()
doc: Option[com.mongodb.DBObject] = Some({ "_id" : "some" , "value" : 0})
scala> doc("_id")
<console>:13: error: Option[com.mongodb.DBObject] does not take parameters
doc("_id")
^
scala>
Casbah API doesn't know the contents of your database and cannot be sure that record you are asking for really exists. In Java such method would simply return object that can be null
. This is discouraged in Scala in faviour of safer Option[T]
type. This way you are forced to handle a situation where object didn't exist. You have several syntaxes for that (from worst to best:
col.findOne().get
col.findOne() match {
case Some(r) => //r is your record
case None => //record didn't exist
}
col.findOne().map(r => r("_id")).foreach(println)
The code above will print the _id
column only if such record was found - and do nothing otherwise.