Overview
In this guide, you can learn how to use a connection string and MongoClient object
to connect to different types of MongoDB deployments.
Atlas
To connect to a MongoDB deployment on Atlas, include the following elements in your connection string:
URL of your Atlas cluster
MongoDB username
MongoDB password
Then, pass your connection string to the MongoClient.create() method.
Tip
Follow the Atlas driver connection guide to retrieve your connection string.
When you connect to Atlas, we recommend using the Stable API client option to avoid breaking changes when Atlas upgrades to a new version of MongoDB server. To learn more about the Stable API feature, see the Stable API page.
The following code shows how to use the Kotlin driver to connect to an Atlas cluster. The
code also uses the serverApi option to specify a Stable API version:
// Replace the placeholder with your Atlas connection string val uri = "<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(uri)) .serverApi(serverApi) .build() // Create a new client and connect to the server val mongoClient = MongoClient.create(settings) val database = mongoClient.getDatabase("admin") try { // Send a ping to confirm a successful connection val command = Document("ping", BsonInt64(1)) val commandResult = database.runCommand(command) println("Pinged your deployment. You successfully connected to MongoDB!") } catch (me: MongoException) { System.err.println(me) }
Local Deployments
To connect to a local MongoDB deployment, use localhost as the hostname. By
default, the mongod process runs on port 27017, though you can customize this for
your deployment.
The following code shows how to use the Kotlin driver to connect to a local MongoDB deployment:
import com.mongodb.kotlin.client.coroutine.MongoClient val uri = "mongodb://localhost:27017/" val client = MongoClient.create(uri)
Replica Sets
A MongoDB replica set deployment is a group of connected instances that store the same set of data. This configuration of instances provides data redundancy and high data availability.
To connect to a replica set, specify the hostnames (or IP addresses) and port numbers of the replica-set members.
If you aren't able to provide a full list of hosts in the replica set, you can specify one or more of the hosts in the replica set and instruct the Kotlin driver to perform automatic discovery to find the others. To instruct the driver to perform automatic discovery, perform one of the following actions:
Specify the name of the replica set as the value of the
replicaSetparameter.Specify
falseas the value of thedirectConnectionparameter.Specify more than one host in the replica set.
Note
The MongoClient constructor is non-blocking.
When you connect to a replica set, the constructor returns immediately while the
client uses background threads to connect to the replica set.
If you construct a MongoClient and immediately print the string representation
of its nodes attribute, the list might be empty while the client connects to
the replica-set members.
The following examples show how to connect to a MongoDB replica set running on port
27017 of three different hosts by using either the ConnectionString or
MongoClientSettings class. Select the tab that corresponds to your preferred class.
val connectionString = ConnectionString("mongodb://host1:27017,host2:27017,host3:27017/") val mongoClient = MongoClient.create(connectionString)
val seed1 = ServerAddress("host1", 27017) val seed2 = ServerAddress("host2", 27017) val seed3 = ServerAddress("host3", 27017) val settings = MongoClientSettings.builder() .applyToClusterSettings { builder -> builder.hosts( listOf(seed1, seed2, seed3) ) } .build() val mongoClient = MongoClient.create(settings)
Note
Replica Set in Docker
When a replica set runs in Docker, it might expose only one MongoDB endpoint.
In this case, the replica set is not discoverable. Specifying directConnection=false in your connection URI,
or leaving this option unset, can prevent your application from connecting to it.
In a test or development environment, you can connect to the replica set by specifying
directConnection=true. In a production environment, we
recommend configuring the cluster to make each MongoDB instance accessible outside of
the Docker virtual network.
DNS Service Discovery
To use DNS service discovery to look up the DNS SRV record of the service you're connecting to, specify the SRV connection format in your connection string. Additionally, if you enable the SRV connection format, the Kotlin driver automatically re-scans for new hosts without having to change the client configuration.
The following code shows a connection string that uses the SRV connection format:
val uri = "mongodb+srv://<hostname>/"
To learn more about the SRV connection format, see the SRV Connection Format entry in the MongoDB server manual.
API Documentation
To learn more about creating a MongoClient object in the Kotlin driver,
see the following API documentation: