Casbah Scala MongoDB Driver - Retrieving Data from DBObject

So here is another question about the basics of Casbah and MongoDB. After I deleted DBObject from the database, how do I extract certain data from it? I know that there is a DBObject.get() method that returns java.lang.Object . Should I do it like this and then just pass the data to the right type? I'm not sure if this is the best way to do this ... can anyone recommend a better way to do this?

UPDATE:

Finally, I went about manually managing all of this. I do not use Salat because of the limitation of the case class, because class classes are not recommended in order to have children, and this will require architectural restructuring. However, the answer is marked as the best answer, as it will work in most situations, and there is no other more general answer here.

+7
source share
2 answers

You can use the MongoDBObject as method to get the value and make it one call:

 val coll = MongoConnection()(dbName)(collName) val query = MongoDBObject("title" -> "some value") val obj = coll findOne query val someStr = obj.as[String]("title") val someInt = obj.as[Int]("count") // and so on.. 

Note that as throws an exception if the specified key is not found. You can use getAs , which gives you Option[A] :

 obj.getAs[String]("title") match { case Some(someStr) => ... case None => ... } 

Retrieving lists is a bit more complicated:

 val myListOfInts = (List() ++ obj("nums").asInstanceOf[BasicDBList]) map { _.asInstanceOf[Int] } 

I wrote an assistant that makes using casbah more demise, maybe it will be useful, so I attach it:

 package utils import com.mongodb.casbah.Imports._ class DBObjectHelper(underlying: DBObject) { def asString(key: String) = underlying.as[String](key) def asDouble(key: String) = underlying.as[Double](key) def asInt(key: String) = underlying.as[Int](key) def asList[A](key: String) = (List() ++ underlying(key).asInstanceOf[BasicDBList]) map { _.asInstanceOf[A] } def asDoubleList(key: String) = asList[Double](key) } object DBObjectHelper { implicit def toDBObjectHelper(obj: DBObject) = new DBObjectHelper(obj) } 

You can use the helper helper:

 val someStr = obj asString "title" val someInt = obj asInt "count" val myDoubleList = obj asDoubleList "coords" 

Hope this helps you.

+11
source

If you are not afraid to use additional dependencies, use Salat . Using Salat makes it very easy to classify case classes for a database object and vice versa.

serialization

 val dbo = grater[Company].asDBObject(company) 

deserialization

 val company_* = grater[Company].asObject(dbo) 
+2
source

All Articles