开发者

which driver can i use to access mongodb in scala swing application?

HI.. I am working with the scala n mongodb. now i want access mongodb database in scala swing application. so which drivers can i use for it? and which can easi开发者_运维技巧ly work? please reply


I've been using casbah http://api.mongodb.org/scala/casbah/2.0.2/index.html to talk to mongodb from my scala swing application.

It's pretty easy to install and setup, and the API is quite scala-esque.

The hardest part is understanding mongodb itself, (coming from an sql background)


We were sort of unsatisfied with the way Casbah works for deep objects or simple maps and no real case class mapping support so we rolled our own MongoDB Synchronous Scala driver on top of the legacy java driver which I would like to shamelessly plug here with an example on how to store and retrieve a map and a simple case class. The driver does not have a lot of magic and is easy to setup and features a simple BSON implementation which was inspired by the Play2 JSON impl.

Here is how to use it with some simple values:

val client = MongoClient("hostname", 27017)
val db = client("dbname")
val coll = db("collectionname")

coll.save(Bson.doc("_id" -> 1, "vals" -> Map("key1" -> "val1")))
val docOpt = coll.findOneById(1)  // => Option[BsonDoc]

for(doc <- docOpt)
  println(doc.as[Map[String, String]]("vals")("key1"))  // => prints "val1"

For a case class it is a little bit more complex but it is all handrolled and there is no magic involved so you can do whatever you like and how you need it, i.e. provider some shorter key names in the doc:

case class DnsRecord(host: String = "", ttl: Long = 0, otherProps: Map[String, String] = Map())

case object DnsRecord {
  implicit object DnsRecordToBsonElement extends ToBsonElement[DnsRecord] {
    def toBson(v: DnsRecord): BsonElement = DnsRecordToBsonDoc.toBson(v)
  }

  implicit object DnsRecordFromBsonElement extends FromBsonElement[DnsRecord] {
    def fromBson(v: BsonElement): DnsRecord = DnsRecordFromBsonDoc.fromBson(v.asInstanceOf[BsonDoc])
  }

  implicit object DnsRecordFromBsonDoc extends FromBsonDoc[DnsRecord] {
    def fromBson(d: BsonDoc): DnsRecord = DnsRecord(
      d[String]("host"),
      d[Long]("ttl"),
      d[Map[String, String]]("op")
    )
  }

  implicit object DnsRecordToBsonDoc extends ToBsonDoc[DnsRecord] {
    def toBson(m: DnsRecord): BsonDoc = Bson.doc(
      "host" -> m.host,
      "ttl" -> m.ttl,
      "op" -> m.otherProps
    )
  }
}

coll.save(DnsRecord("test.de", 4456, Map("p2" -> "val1")))
for (r <- coll.findAs[DnsRecord](Bson.doc("host" -> "test.de")))
  println(r.host)


As an update for people finding this thread and interested in MongoDB 3.X. We're using Async driver which can be found here https://github.com/evojam/mongodb-driver-scala. It's API is build in Scala way with new Play 2.4 module ready if you're using it, but you can always take only driver.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜