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.
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.