Docs Menu
Docs Home
/ / /
Kotlin Coroutine
/ /

Connect to MongoDB

In this guide, you can learn how to connect to a MongoDB instance or replica set using the Kotlin driver.

You can view sample code to connect to an Atlas cluster or continue reading to learn more about the MongoClient class and connection URIs.

You can connect to and communicate with MongoDB using the MongoClient class.

Use the MongoClient.create() method to construct a MongoClient.

Important

Reuse Your Client

As each MongoClient represents a thread-safe pool of connections to the database, most applications only require a single instance of a MongoClient, even across multiple threads.

To learn more about how connection pools work in the driver, see the FAQ page.

All resource usage limits, such as max connections, apply to individual MongoClient instances.

To learn about the different settings you can use to control the behavior of your MongoClient, see the guide on MongoClient Settings.

Tip

Always call MongoClient.close() to clean up resources when an instance is no longer needed.

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:

Connection String parts figure

This figure uses the Standard Connection String Format, mongodb for the protocol. You can also use the DNS Seed List Connection Format, mongodb+srv, if you want more flexibility of 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 Kotlin from the language dropdown to retrieve your connection string.

The next part of the connection URI contains your credentials if you are using a password-based authentication mechanism. Replace the value of user with your database username and pass with your database user's 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. In the example, we set two connection options: maxPoolSize=20 and w=majority. For more information on connection options, skip to the Connection Options section of this guide.

To connect to a MongoDB deployment on Atlas, create a client. You can create a client that uses your connection string and other client options by passing a MongoClientSettings object to the MongoClient.create() method.

To instantiate a MongoClientSettings object, use the builder method to specify your connection string and any other client options, and then call the build() method. Chain the applyConnectionString() method to the builder to specify your connection URI.

You can set the Stable API version client option to avoid breaking changes when you upgrade to a new server version. To learn more about the Stable API feature, see the Stable API page.

The following code shows how you can specify the connection string and the Stable API client option when connecting to a MongoDB deployment on Atlas and verify that the connection is successful:

// 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)
}

If you are connecting to a single MongoDB server instance or replica set that is not hosted on Atlas, see the following sections to find out how to connect.

If you need to run a MongoDB server on your local machine for development purposes instead of using an Atlas cluster, you need to complete the following:

  1. Download the Community or Enterprise version of MongoDB Server.

  2. Install and configure MongoDB Server.

  3. Start the server.

Important

Always secure your MongoDB server from malicious attacks. See our Security Checklist for a list of security recommendations.

After you successfully start your MongoDB server, specify your connection string in your driver connection code.

If your MongoDB Server is running locally, you can use the connection string "mongodb://localhost:<port>" where <port> is the port number you configured your server to listen for incoming connections.

If you need to specify a different hostname or IP address, see our Server Manual entry on Connection Strings.

To test whether you can connect to your server, replace the connection string in the Connect to MongoDB Atlas code example and run it.

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 deployment, specify the hostnames (or IP addresses) and port numbers of the members of the replica set.

If you are not able to provide a full list of hosts in the replica set, you can specify a single or subset of the hosts in the replica and instruct the driver to perform automatic discovery in one of the following ways:

  • Specify the name of the replica set as the value of the replicaSet parameter

  • Specify false as the value of the directConnection parameter

  • Specify more than one host in the replica set

Tip

Although you can specify a subset of the hosts in a replica set, include all the hosts in the replica set to ensure the driver is able to establish the connection if one of the hosts are unreachable.

The following examples show how to specify multiple hosts to a MongoClient instance 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)

Back

Connection Guide