Docs Menu
Docs Home
/ / /
Scala
/

Connect to MongoDB

On this page

  • Prerequisites
  • MongoClient
  • Connection URI
  • Connect to MongoDB Atlas
  • Connect to a Local MongoDB Deployment
  • Connect to a Replica Set
  • Connect to a Sharded Cluster
  • Connection Options
  • Connection Tutorials

This guide describes how to use the Scala driver to connect to MongoDB.

Use the MongoClient() method to make a connection to a running MongoDB deployment.

Important

The following examples do not provide an exhaustive list of ways to instantiate a MongoClient. For a complete list of the MongoClient companion methods, see the MongoClient API documentation.

Note

We strongly recommended that system keep-alive settings should be configured with shorter timeouts.

See the Does TCP keepalive time affect MongoDB Deployments? question and answer in the Server manual FAQ for more information.

You must set up the following components to run the code examples in this guide:

  • A running MongoDB deployment to connect to. For example, to connect to a standalone deployment, you must have access to a running standalone deployment.

  • Driver dependency installed in your project. To learn how to install the driver, see Installation.

  • The following import statements:

    import org.mongodb.scala._
    import scala.collection.JavaConverters._

A MongoClient instance represents a pool of connections to the database. You need only one instance of MongoClient even when running multiple concurrent operations.

Important

Typically, you create only one MongoClient instance for a given MongoDB deployment, such as a standalone deployment, replica set, or a sharded cluster, and use the client across your application. However, if you do create multiple instances, keep the following in mind:

  • All resource-usage limits (for example, max connections) apply to each MongoClient instance.

  • To dispose of an instance, call the MongoClient.close() method to clean up resources.

The connection URI provides a set of instructions that the driver uses to connect to a MongoDB deployment. It instructs the driver on how it should connect to MongoDB and how it should behave while connected. The following figure explains each part of a sample connection URI:

An example of a connection string that demonstrates the protocol, credentials, hostname or IP, port, and connection options

In this example, you connect to an Atlas MongoDB deployment that has a DNS SRV record. For more details, see the DNS Seed List Connection Format documentation. This format offers flexibility in deployment and the ability to change the servers in rotation without reconfiguring clients.

Note

If your deployment is on MongoDB Atlas, see the Atlas driver connection guide and select Scala from the language dropdown to retrieve your connection string.

If you are connecting to an instance or replica set that does not have a DNS SRV address, you must use mongodb for the protocol, which specifies the Standard Connection String Format.

After the protocol, the connection string contains your credentials if you are using a password-based authentication mechanism. Replace the value of user with your username and pass with your password. If your authentication mechanism does not require credentials, omit this part of the connection URI.

The next part of the connection URI specifies the hostname or IP address, followed by the port of your MongoDB instance. In the example, sample.host represents the hostname and 27017 is the port number. Replace these values to refer to your MongoDB instance.

The last part of the connection URI contains connection options as parameters. The example sets two connection options: maxPoolSize=20 and w=majority.

You can use the following connection snippet to test your connection to your MongoDB deployment on Atlas:

import com.mongodb.{ServerApi, ServerApiVersion}
import org.mongodb.scala.{ConnectionString, MongoClient, MongoClientSettings}
import org.mongodb.scala.bson.Document
import scala.concurrent.Await
import scala.concurrent.duration.DurationInt
import scala.util.Using
object MongoClientConnectionExample {
def main(args: Array[String]): Unit = {
// Replace the placeholder with your Atlas connection string
val connectionString = "<connection string>";
// Construct a ServerApi instance using the ServerApi.builder() method
val serverApi = ServerApi.builder.version(ServerApiVersion.V1).build()
val settings = MongoClientSettings
.builder()
.applyConnectionString(ConnectionString(connectionString))
.serverApi(serverApi)
.build()
// Create a new client and connect to the server
Using(MongoClient(settings)) { mongoClient =>
// Send a ping to confirm a successful connection
val database = mongoClient.getDatabase("admin")
val ping = database.runCommand(Document("ping" -> 1)).head()
Await.result(ping, 10.seconds)
System.out.println("Pinged your deployment. You successfully connected to MongoDB!")
}
}
}

This connection snippet uses the Stable API feature, which you can enable when using the Scala driver v4.3 and later to connect to MongoDB Server v5.0 and later. When you use this feature, you can update your driver or server without worrying about backward compatibility issues with any commands covered by the Stable API.

To learn more about the Stable API feature, see Stable API in the Server manual.

You can connect to a local MongoDB deployment in the following ways:

  • Instantiate a MongoClient object without any parameters to connect to a MongoDB server running on localhost on port 27017:

    val mongoClient = MongoClient()
  • Explicitly specify the hostname to connect to a MongoDB instance running on the specified host on port 27017:

    val mongoClient = MongoClient("mongodb://host1")
  • Explicitly specify the hostname and the port:

    val mongoClient = MongoClient("mongodb://host1:27017")

To connect to a replica set, you must specify one or more members to the MongoClient apply method. To learn more about replica sets, see Replication in the Server manual.

Note

MongoDB auto-discovers the primary and secondary nodes in a replica set.

You can connect to a MongoDB replica set by specifying the members in a ConnectionString.

The following example shows how to specify three members of the replica set:

val mongoClient = MongoClient("mongodb://host1:27017,host2:27017,host3:27017")

The following example shows how to specify members of the replica set and the replicaSet option with the replica set name:

val mongoClient = MongoClient("mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet")

The following example shows how to specify a list of ServerAddress instances corresponding to all of the replica set members:

val mongoClient = MongoClient(
MongoClientSettings.builder()
.applyToClusterSettings((builder: ClusterSettings.Builder) => builder.hosts(List(
new ServerAddress("host1", 27017),
new ServerAddress("host2", 27017),
new ServerAddress("host3", 27017)).asJava))
.build())

To connect to a sharded cluster, specify the mongos instance or instances to the MongoClient apply method. To learn more about sharded clusters, see Sharding in the Server manual.

You can connect to a single mongos instance in the following ways:

  • Specify the hostname and the port in a ConnectionString:

    val mongoClient = MongoClient( "mongodb://localhost:27017" )
  • Exclude connection string if the mongos is running on localhost:27017:

    val mongoClient = MongoClient()

You can connect to multiple mongos instances in the following ways:

  • Specify the ConnectionString to contain their hostnames and ports:

    val mongoClient = MongoClient("mongodb://host1:27017,host2:27017")
  • Specify a list of the ServerAddress objects corresponding to each instance:

    val mongoClient = MongoClient(
    MongoClientSettings.builder()
    .applyToClusterSettings((builder: ClusterSettings.Builder) => builder.hosts(List(
    new ServerAddress("host1", 27017),
    new ServerAddress("host2", 27017)).asJava))
    .build())

You can specify connection settings by using either the ConnectionString or MongoClientSettings types, or both.

For example, you can specify TLS/SSL and authentication settings in the connection string:

val mongoClient = MongoClient("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true")

You can also use a MongoClientSettings instance to specify TLS/SSL and the MongoCredential type to store the authentication information:

val user: String = // the user name
val source: String = // the source where the user is defined
val password: Array[Char] = // the password as a character array
// ...
val credential = MongoCredential.createCredential(user, source, password)
val mongoClient: MongoClient = MongoClient(
MongoClientSettings.builder()
.applyToSslSettings((builder: SslSettings.Builder) => builder.enabled(true))
.applyToClusterSettings((builder: ClusterSettings.Builder) => builder.hosts(List(new ServerAddress("host1", 27017)).asJava))
.credential(credential)
.build())

In some cases, you might need to combine a connection string with programmatic configuration:

val connectionString = ConnectionString("mongodb://host1:27107,host2:27017/?ssl=true")
val myCommandListener: CommandListener = ???
val mongoClient = MongoClient(
MongoClientSettings.builder()
.addCommandListener(myCommandListener)
.applyConnectionString(connectionString)
.build())

To learn how to implement other connection features, see the following tutorials:

Back

Tutorials