Connecting to MongoDB with Casbah

The official MongoDB driver for Scala is called Casbah. Rather than a fully-fledged driver, Casbah wraps the Java Mongo driver, providing a more functional interface. There are other MongoDB drivers for Scala, which we will discuss briefly at the end of this chapter. For now, we will stick to Casbah.

Let's start by adding Casbah to our build.sbt file:

scalaVersion := "2.11.7"

libraryDependencies += "org.mongodb" %% "casbah" % "3.0.0"

Casbah also expects slf4j bindings (a Scala logging framework) to be available, so let's also add slf4j-nop:

libraryDependencies += "org.slf4j" % "slf4j-nop" % "1.7.12"

We can now start an SBT console and import Casbah in the Scala shell:

$ sbt console
scala> import com.mongodb.casbah.Imports._
import com.mongodb.casbah.Imports._

scala> val client = MongoClient()
client: com.mongodb.casbah.MongoClient = com.mongodb.casbah.MongoClient@4ac17318

This connects to a MongoDB server on the default host (localhost) and default port (27017). To connect to a different server, pass the host and port as arguments to MongoClient:

scala> val client = MongoClient("192.168.1.1", 27017)
client: com.mongodb.casbah.MongoClient = com.mongodb.casbah.MongoClient@584c6b02

Note that creating a client is a lazy operation: it does not attempt to connect to the server until it needs to. This means that if you enter the wrong URL or password, you will not know about it until you try and access documents on the server.

Once we have a connection to the server, accessing a database is as simple as using the client's apply method. For instance, to access the github database:

scala> val db = client("github")
db: com.mongodb.casbah.MongoDB = DB{name='github'}

We can then access the "users" collection:

scala> val coll = db("users")
coll: com.mongodb.casbah.MongoCollection = users

Connecting with authentication

MongoDB supports several different authentication mechanisms. In this section, we will assume that your server is using the SCRAM-SHA-1 mechanism, but you should find adapting the code to a different type of authentication straightforward.

The easiest way of authenticating is to pass username and password in the URI when connecting:

scala> val username = "USER"
username: String = USER

scala> val password = "PASSWORD"
password: String = PASSWORD

scala> val uri = MongoClientURI(
  s"mongodb://$username:$password@localhost/?authMechanism=SCRAM-SHA-1"
)
uri: MongoClientURI = mongodb://USER:PASSWORD@localhost/?authMechanism=SCRAM-SHA-1

scala> val mongoClient = MongoClient(uri)
client: com.mongodb.casbah.MongoClient = com.mongodb.casbah.MongoClient@4ac17318

In general, you will not want to put your password in plain text in the code. You can either prompt for a password on the command line or pass it through environment variables, as we did with the GitHub OAuth token in Chapter 7, Web APIs. The following code snippet demonstrates how to pass credentials through the environment:

// Credentials.scala

import com.mongodb.casbah.Imports._

object Credentials extends App {

  val username = sys.env.getOrElse("MONGOUSER",
    throw new IllegalStateException(
      "Need a MONGOUSER variable in the environment")
  )
  val password = sys.env.getOrElse("MONGOPASSWORD",
    throw new IllegalStateException(
      "Need a MONGOPASSWORD variable in the environment")
  )

  val host = "127.0.0.1"
  val port = 27017

  val uri = s"mongodb://$username:$password@$host:$port/?authMechanism=SCRAM-SHA-1"

  val client = MongoClient(MongoClientURI(uri))
}

You can run it through SBT as follows:

$ MONGOUSER="pascal" MONGOPASSWORD="scalarulez" sbt
> runMain Credentials
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.246.148