Get Started with the Scala Driver
On this page
- Overview
- Download and Install
- Install dependencies
- Create a project directory
- Configure your project to use the Scala driver
- Create a MongoDB Deployment
- Create a free MongoDB deployment on Atlas
- Save your credentials
- Create a Connection String
- Find your MongoDB Atlas Connection String
- Copy your Connection String
- Update the Placeholders
- Connect to MongoDB
- Create an application file
- Add helper methods
- Add your application code
- Assign the connection string
- Run your Scala application
- Next Steps
Overview
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.
Download and Install
Create a project directory
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
Configure your project to use the Scala driver
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.
Create a MongoDB Deployment
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.
Create a free MongoDB deployment on Atlas
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.
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.
Create a Connection String
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.
Find your MongoDB Atlas Connection String
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.

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.
After you complete these steps, you have a connection string that corresponds to your Atlas cluster.
Connect to MongoDB
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.
Create an application file
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
Add helper methods
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.
Add your application code
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() } }
Assign the connection string
Replace the <connection string>
placeholder with the
connection string that you copied from the Create a Connection String
step of this guide.
Run your Scala application
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.
Next Steps
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:
Learn how to perform read operations in the Read Data section.
Learn how to perform write operations in the Write Data to MongoDB section.
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.