0

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!

Anton Ashanin
  • 1,817
  • 5
  • 30
  • 43

1 Answers1

0

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

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • Does it mean that in Casbah I can not open connection to Mongo without creating some collection? – Anton Ashanin Mar 21 '13 at 21:17
  • @AntonAshanin you can (check mongo log), but what is point of connecting to mongo and lurking for a collection that doesn't exists yet and doing just nothing? – om-nom-nom Mar 21 '13 at 21:20
  • How can one check with Casbah that Mongo is up and running without creating some database and collection? Also it would be nice if someone could point me to a simple end-to-end Casbah application example. Thanks! – Anton Ashanin Mar 21 '13 at 21:41
  • @AntonAshanin not sure whether it is the best possible way, but you could try to issue `yourMongoClient.databaseNames`, so you could both check if database is running and if there is target database. – om-nom-nom Mar 21 '13 at 21:51
  • Any simple end-to-end Casbah application example out there? – Anton Ashanin Mar 21 '13 at 22:18