Search code examples
scalamongodbcasbah

Close Connection for Mongodb using Casbah API


I am not getting any useful information about "how to close connection for mongodb using casbah API". Actually, I have defined multiple methods and in each method I need to establish a connection with mongodb. After working I need to close that too. I am using Scala.

one of the method like (code example in scala):

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

def index ={
  val mongoConn = MongoConnection(configuration("hostname"))
  val log = mongoConn("ab")("log")
  val cursor = log.find()
  val data = for {x <- cursor} yield x.getAs[BasicDBObject]("message").get
  html.index(data.toList)
  //mongoConn.close()  <-- here i want to close the connection but this .close() is not working
}

Solution

  • It is unclear, from your question why exactly close is not working. Does it throw some exception, it is not compiling, or has no effect? But since MongoConnection is a thin wrapper over com.mongodb.Mongo, you could work with underlying Mongo directly, just like in plain old Java driver:

    val mongoConn = MongoConnection(configuration("hostname"))
    mongoConn.underlying.close()
    

    Actually, that's exactly, how close is implemented in casbah.