Search code examples
mongodbscalacasbah

Casbah MongoDB toolkit for Scala: can't create connection and collection


I am trying to work with Casbah MongoDB toolkit for Scala. I am running MongoDB on localhost, it works fine. Yet the following code does nothing - no database and no collection get created.And no exception is thrown:

package test.scalamongo

import com.mongodb.casbah.Imports._

object Simple {

  def main(args: Array[String]): Unit = {
try {
  // Connect to default - localhost, 27017
  val mongoClient = MongoClient()
  val mongoDB = mongoClient("casbah_test")
  val mongoColl = mongoClient("casbah_test")("test_data")
  println("Ok now?")
} catch {
  case e: Throwable =>
    println("Exception !!!")
    e.printStackTrace()
}
  }

}

What am I missing? Thanks!


Solution

  • You have to explicitly create collection:

    val mongoClient = MongoClient()
    val mongoDB = mongoClient("casbah_test")
    val mongoColl = 
       if (mongoDB.collectionExists("test_data")) {
         mongoDB("test_data")
       } else mongoDB.createCollection("test_data", options: DBObject)
    

    Possible options:

    capped - boolean: if the collection is capped
    size - int: collection size
    max - int: max number of documents