takayuki_tk's diary

本当はScalaとかHaskellを使いたい

MongoDBとScala -ScalaでMongo

  • コレクションの取得
MongoConnection("localhost")("test")("collections")
  • insert
collection.save(Map("name" -> "takayuki", "work" -> "engineer"))

or

collection += (Map("name" -> "takayuki", "work" -> "engineer"))

or

collection.save(MongoDBObject("name" -> "test3", "work" -> "engineer"))
  • Query DSLを使ったinsert
val doc = MongoDBObject()
doc += "name" -> "hoge"
doc += "work" -> "enginner"
collections += doc

ちなみに += ではなく ++ にするとIterableがかえってきます。(保存はされない。)

おなじIDでもう一度saveすると上書き保存されます。

scala> collection.find().foreach { collection.remove(_) }
scala> collection.save(Map("_id" -> 1, "name" -> "test1"))
res56: com.mongodb.WriteResult = { "serverUsed" : "localhost/127.0.0.1:27017" , "updatedExisting" : false , "n" : 1 , "connectionId" : 1 , "err" :  null  , "ok" : 1.0}
scala> collection.save(Map("_id" -> 1, "name" -> "test1"))
res57: com.mongodb.WriteResult = { "serverUsed" : "localhost/127.0.0.1:27017" , "updatedExisting" : true , "n" : 1 , "connectionId" : 1 , "err" :  null  , "ok" : 1.0}
scala> collection.find().foreach { println }
{ "_id" : 1 , "name" : "test1"}

insertにすると同じIDの場合例外が発生します。

scala> collection.insert(Map("_id" -> 1, "name" -> "test1"))
com.mongodb.MongoException$DuplicateKey: { "serverUsed" : "localhost/127.0.0.1:27017" , "err" : "E11000 duplicate key error index: test.collections.$_id_  dup key: { : 1 }" , "code" : 11000 , "n" : 0 , "connectionId" : 1 , "ok" : 1.0}
at com.mongodb.CommandResult.getException(CommandResult.java:74)