MongoDB® Tutorial: Connecting to MongoDB in Scala

4 min read
MongoDB® Tutorial: Connecting to MongoDB in Scala

SHARE THIS ARTICLE

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 –

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

You can also download MongoDB Scala driver from its github page.

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(
        new ServerAddress("mongodb2.example.com:27345"),
        new ServerAddress("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 systems 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 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, your can add List(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._

object newworld {
  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

Scala driver Getting started pages has examples on how you can test your connection.

References:

Getting started with scala using MongoDB

Mongo Scala API

Let us know if you have any trouble connecting to MongoDB using its Scala driver. We offer managed options for all your MongoDB needs.

For more information, please visit www.scalegrid.io. Connect with ScaleGrid on LinkedIn, X, Facebook, and YouTube.
Table of Contents

Stay Ahead with ScaleGrid Insights

Dive into the world of database management with our monthly newsletter. Get expert tips, in-depth articles, and the latest news, directly to your inbox.

Related Posts

Redis vs Memcached in 2024

Choosing between Redis and Memcached hinges on specific application requirements. In this comparison of Redis vs Memcached, we strip away...

multi cloud plan - scalegrid

Plan Your Multi Cloud Strategy

Thinking about going multi-cloud? A well-planned multi cloud strategy can seriously upgrade your business’s tech game, making you more agile....

hybrid cloud strategy - scalegrid

Mastering Hybrid Cloud Strategy

Mastering Hybrid Cloud Strategy Are you looking to leverage the best private and public cloud worlds to propel your business...

NEWS

Add Headline Here