Deepak Deepak - 1 month ago 7
Scala Question

How do I create a Mongo replicaset connection with Casbah?

I am a newbie to scala and casbah. I am trying to create a mongo replicaset connection using casbah. This is my code. I am pretty sure about my mongo replica setup being correct. When I create a connection through ruby, it works great. Im missing something silly here.
When I googled, I got this documentation and which is what I am using for reference.

http://api.mongodb.org/scala/casbah/current/scaladoc/com/mongodb/casbah/MongoConnection$.html

import com.mongodb.casbah.Imports._

object MongoAnalysisDB {
def main(args: Array[String]) = {
//that connection
val addresses = List("127.0.0.1:27018", "127.0.0.1:27019", "127.0.0.1:27020")
val mongoConn = MongoConnection(replicaSetSeeds: addresses)
val mongoDB = mongoConn("vimana-sandbox-dup")
val mongoColl = mongoConn("vimana-sandbox-dup")("utilization.metrics.cycledowntime")


//that query
val loadEvent = MongoDBObject("period" -> "PT1H")
val cursor = mongoColl.find(loadEvent)
val mtcevent = mongoColl.findOne(loadEvent)

//that document
println(mtcevent)
}
}


I get the following error.

[info] Compiling 1 Scala source to /home/deepak/scala-mongo-oplog-watcher/target/scala-2.9.1/classes...
[error] /home/deepak/scala-mongo-oplog-watcher/src/main/scala/reader.scala:6: ')' expected but '(' found.
[error] val mongoConn = MongoConnection(replicaSetSeeds: List("127.0.0.1:27018", "127.0.0.1:27019", "127.0.0.1:27020"))
[error] ^
[error] /home/deepak/scala-mongo-oplog-watcher/src/main/scala/reader.scala:6: ';' expected but ')' found.
[error] val mongoConn = MongoConnection(replicaSetSeeds: List("127.0.0.1:27018", "127.0.0.1:27019", "127.0.0.1:27020"))
[error] ^
[error] two errors found
[error] {file:/home/deepak/scala-mongo-oplog-watcher/}default-b16d47/compile:compile: Compilation failed

Answer

Wrapping up the ip string and port into ServerAddress worked.

import com.mongodb._ 
import com.mongodb.casbah.Imports._ 

object MongoAnalysisDB {
  def main(args: Array[String]) = {
    //that connection
    val addresses = List(new ServerAddress("127.0.0.1" , 27018),  new ServerAddress("127.0.0.1" , 27019),  new ServerAddress( "127.0.0.1" , 27020 ))
    val mongoConn = MongoConnection(addresses) 
    val mongoDB = mongoConn("vimana-sandbox-dup") 
    val mongoColl = mongoConn("vimana-sandbox-dup")("utilization.metrics.cycledowntime") 


    //that query
    val loadEvent = MongoDBObject("period" -> "PT1H") 
    val cursor = mongoColl.find(loadEvent)
    val mtcevent = mongoColl.findOne(loadEvent)

    //that document
    println(mtcevent)
  }
}

See also: http://mongodb.github.io/casbah/3.1/reference/connecting/#connecting-to-replicasets-mongos

Comments