简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM