Connecting to MongoDB in Scala

MongoDB has an extensive driver set for many programming languages. In the following tutorial, we will show you the various nuances of connecting to MongoDB using its Scala driver.

Driver Installation

MongoDB’s Scala driver can be added to your project using the following dependency:

<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-scala-driver</artifactId>
<version>1.0.1</version>
</dependency>
</dependencies>


You can also download the MongoDB Scala driver from its GitHub page.

The Scala driver for MongoDB, like Java, comes with multiple classes to facilitate connections to a MongoDB instance.

Let’s take this step by step:

Connection

A connection to a MongoDB instance can be set up using a Mongo client. MongoClient is a class that can be used to manage connections to MongoDB. The simplest way to create a connection would be by using -

val client:MongoClient=MongoClient("<server1>:27017")


Options such as authentication, port number etc. can be set in the connection string. For example, a replica set option can be set as /?replicaSet=rs0. For a complete list of options visit connection string URI options.

Alternatively, a MongoClientSettings() class can be used to control the behavior of a Mongo Client. A ClusterSettings class be used to add cluster settings to the Mongoclientsettings class. A simple connection using these three classes can be as follows -

val clusterSettings: ClusterSettings=ClusterSettings.builder()
.hosts(List(newServerAddress("mongodb2.example.com:27345")
,newServerAddress("mongodb1.example.com:20026")).asJava).build()
val settings: <MongoClientSettings=MongoClientSettings.builder()
.clusterSettings(clusterSettings)).build()
val mongoClient: MongoClient=MongoClient(settings)


The connection, by default, uses AsynchronousSocketChannel from your system's JDK — if you are using SSL or have a JDK version earlier than 1.7, you will need to use Netty as described in the SSL section.

SSL

Your connection to MongoDB can be secured using SSL. Our other blog post 'Securing clusters with SSL' describes the importance of SSL.

To validate the certificate presented by the MongoDB server you will need to add the signing authorities CA to the system’s trust store.

You will also need to add properties for the driver in order to use a Netty library instead of AsynchronousSocketChannel for this purpose. You will need to download the Netty JARs and add them to your current projects as the Scala dependency does not download it. You will also need the following import statements: 

import org.mongodb.scala.connection.{NettyStreamFactoryFactory,SslSettings}


The connection to MongoDB using SSL can be made as follows:

val settings: MongoClientSettings=MongoClientSettings.builder()
.clusterSettings(clusterSettings)
.sslSettings(SslSettings.builder().enabled(true).build())
.streamFactoryFactory(NettyStreamFactoryFactory()).build()


If you have issues connecting to the server, then the host name on your server’s SSL certificate might be different than the one that you specify while building the MongoClient. You can disable this setting by using. .invalidHostNameAllowed(true) in your SslSettings.

Authentication

You can use the MongoCredential class to add credentials to your MongoClientSettings. A typical usage of the MongoCredentials class will be as follows:

val settings: MongoClientSettings = MongoClientSettings.builder()
.clusterSettings(clusterSettings).credentialList(credential)
.sslSettings(SslSettings.builder().enabled(true).build())
.streamFactoryFactory(NettyStreamFactoryFactory())
.build()


Note that when you have added more than one host in the cluster settings, then you can add your credentials as a List. For example, you can addList(credential1,credential2).asJava  for two hosts.

Putting it all together, here is the complete code to connect to a replica set with SSL in Scala:

import com.mongodb.MongoCredential
import org.mongodb.scala.bson.collection.mutable.Document
import org.mongodb.scala.{Completed, FindObservable, MongoClient, MongoClientSettings, MongoCollection, MongoDatabase, Observable,Observer, ReadPreference, ServerAddress}
import org.mongodb.scala.connection.ClusterSettings
import com.mongodb.MongoCredential._
import java.util.logging.{Level, Logger}
import org.mongodb.scala.connection.{NettyStreamFactoryFactory,SslSettings}
import scala.collection.JavaConverters._
objectnewworld {
    def main(args: Array[String]): Unit = {val mongoLogger: Logger = Logger.getLogger("com.mongodb")
        mongoLogger.setLevel(Level.SEVERE);
        val clusterSettings: ClusterSettings = ClusterSettings.builder().hosts(List(new ServerAddress("example.com:27345"), new ServerAddress("example.com:20026")).asJava).build()
        val user: String = "testuser"
        val databasename: String = "scalatest"
        val password: Array[Char] = "<enter-a-password>".toCharArray
        val credential: MongoCredential = createCredential(user, databasename, password)
        val settings: MongoClientSettings = MongoClientSettings.builder()
        .clusterSettings(clusterSettings).credentialList(List(credential,credential).asJava).sslSettings(SslSettings.builder().enabled(true).build())
        .streamFactoryFactory(NettyStreamFactoryFactory()).build()
        val mongoClient: MongoClient = MongoClient(settings)
        val database: MongoDatabase = mongoClient.getDatabase("scalatest")
        mongoClient.close()
    }
}


Testing Your Connection

And there you have it. Of course, you probably want to make sure everything's working well. For that, the driver's getting started pages have examples on how you can test your connection.

 

 

 

 

Top