Docs Menu

Get Started with the Scala Driver

The MongoDB Scala Driver is an asynchronous API built upon the Java Reactive Streams driver, which you can use to connect to MongoDB and interact with data stored in your deployment. This guide shows you how to create an application that uses the Scala driver to connect to a MongoDB cluster hosted on MongoDB Atlas and query data in your cluster.

Tip

MongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. You can create your own free (no credit card required) MongoDB Atlas deployment by following the steps in this guide.

Follow this guide to connect a sample Scala application to a MongoDB Atlas deployment. If you prefer to connect to MongoDB using a different driver or programming language, see our list of official drivers.

1

Before you being developing, ensure you have the following dependencies installed in your development environment:

  • JDK version 8 or later

  • sbt version 1 or later

2

Run the following command in your shell to create a directory called scala-quickstart for this project:

mkdir scala-quickstart

Select the tab corresponding to your operating system and run the following commands to create a build.sbt file in the scala-quickstart directory:

cd scala-quickstart
touch build.sbt
cd scala-quickstart
type nul > build.sbt
3

Navigate to your build.sbt file and add the following code to use the Scala driver in your application:

ThisBuild / scalaVersion := "2.13.16"
libraryDependencies += "org.mongodb.scala" %% "mongo-scala-driver" % "5.4.0"

This code configures your application to use Scala version 2.13.16 and Scala driver version 5.4.0.

After you complete these steps, you have a new project directory with the driver dependencies installed.

You can create a free tier MongoDB deployment on MongoDB Atlas to store and manage your data. MongoDB Atlas hosts and manages your MongoDB database in the cloud.

1

Complete the Get Started with Atlas guide to set up a new Atlas account and load sample data into a new free tier MongoDB deployment.

2

After you create your database user, save that user's username and password to a safe location for use in an upcoming step.

After you complete these steps, you have a new free tier MongoDB deployment on Atlas, database user credentials, and sample data loaded into your database.

You can connect to your MongoDB deployment by providing a connection URI, also called a connection string, which instructs the driver on how to connect to a MongoDB deployment and how to behave while connected.

The connection string includes the hostname or IP address and port of your deployment, the authentication mechanism, user credentials when applicable, and connection options.

To learn how to connect to an instance or deployment not hosted on Atlas, see the Choose a Connection Target guide.

1

To retrieve your connection string for the deployment that you created in the previous step, log in to your Atlas account and navigate to the Database section and click the Connect button for your new deployment.

The connect button in the clusters section of the Atlas UI

Then, select the Drivers option under the Connect to your application header. Select "Scala" from the Driver selection menu and the version that best matches the version you installed from the Version selection menu.

2

Click the button on the right of the connection string to copy it to your clipboard, as shown in the following screenshot:

The copy button next to the connection string in the Atlas UI
3

Paste this connection string into a file in your preferred text editor and replace the <db_username> and <db_password> placeholders with your database user's username and password.

Save this file to a safe location for use in the next step.

After you complete these steps, you have a connection string that corresponds to your Atlas cluster.

After retrieving the connection string for your MongoDB Atlas deployment, you can connect to the deployment from your Scala application and query the Atlas sample datasets.

1

Navigate to the scala-quickstart directory that you made in the Download and Install step of this guide and create the src/main/scala/quickstart nested directories.

Select the tab corresponding to your operating system and run the following commands to create a Main.scala file in the quickstart subdirectory:

cd src/main/scala/quickstart
touch Main.scala
cd src/main/scala/quickstart
type nul > Main.scala
2

Add the following Helpers.scala file from the driver source code to the src/main/scala/quickstart directory:

package quickstart
import java.util.concurrent.TimeUnit
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import org.mongodb.scala._
object Helpers {
implicit class DocumentObservable[C](val observable: Observable[Document]) extends ImplicitObservable[Document] {
override val converter: (Document) => String = (doc) => doc.toJson
}
implicit class GenericObservable[C](val observable: Observable[C]) extends ImplicitObservable[C] {
override val converter: (C) => String = (doc) => Option(doc).map(_.toString).getOrElse("")
}
trait ImplicitObservable[C] {
val observable: Observable[C]
val converter: (C) => String
def results(): Seq[C] = Await.result(observable.toFuture(), Duration(10, TimeUnit.SECONDS))
def headResult() = Await.result(observable.head(), Duration(10, TimeUnit.SECONDS))
def printResults(initial: String = ""): Unit = {
if (initial.length > 0) print(initial)
results().foreach(res => println(converter(res)))
}
def printHeadResult(initial: String = ""): Unit = println(s"${initial}${converter(headResult())}")
}
}

This file allows you to access helper methods for printing query results.

3

Copy and paste the following code into the Main.scala file, which queries the movies collection in the sample_mflix database:

package quickstart
import org.mongodb.scala._
import org.mongodb.scala.model.Filters._
import Helpers._
object Main {
def main(args: Array[String]): Unit = {
val mongoClient = MongoClient("<connection string>")
val database: MongoDatabase =
mongoClient.getDatabase("sample_mflix")
val collection: MongoCollection[Document] =
database.getCollection("movies")
val filter = equal("title", "The Shawshank Redemption")
collection.find(filter).printResults()
mongoClient.close()
}
}
4

Replace the <connection string> placeholder with the connection string that you copied from the Create a Connection String step of this guide.

5

In your project root directory, run the following commands to start the sbt shell and run your application:

sbt
run

The command line output contains details about the retrieved movie document:

{"_id": {"$oid": "..."}, ... , "genres": ["Crime", "Drama"], "rated": "R",
"metacritic": 80, "title": "The Shawshank Redemption", ... }

If you encounter an error or see no output, ensure that you specified the proper connection string in the Main.scala file and that you loaded the sample data.

Tip

You can exit the sbt shell by running the following command:

exit

After you complete these steps, you have a Scala application that connects to your MongoDB deployment, runs a query on the sample data, and returns a matching document.

Congratulations on completing the quick start tutorial!

In this tutorial, you created a Scala application that connects to a MongoDB deployment hosted on MongoDB Atlas and retrieves a document that matches a query.

Learn more about Scala driver from the following resources:

Note

If you run into issues on this step, ask for help in the MongoDB Community Forums or submit feedback by using the Rate this page tab on the right or bottom right side of this page.