Connect to MongoDB from Kotlin

Connect to MongoDB from Kotlin – In this tutorial, we shall learn to connect to MongoDB from Kotlin Application.

A Kotlin application connects to MongoDB by adding a MongoDB driver dependency, creating a MongoClient, and using a connection string such as mongodb://localhost:27017/ for a local server or mongodb+srv://... for MongoDB Atlas.

This page keeps the original legacy Java driver example and adds current Kotlin driver examples. For new Kotlin/JVM projects, use the Kotlin Sync driver for blocking code or the Kotlin Coroutine driver for coroutine-based applications.

Prerequisites for Kotlin MongoDB connection

  • Kotlin/JVM project in IntelliJ IDEA, Eclipse, Gradle, or Maven.
  • JDK installed and configured.
  • MongoDB running locally or a MongoDB Atlas cluster.
  • Correct host, port, database user, password, and network access settings.

Kotlin MongoDB driver options

Driver styleUse it forDependencyMongoClient import
Kotlin Sync driverSimple blocking Kotlin/JVM code.mongodb-driver-kotlin-synccom.mongodb.kotlin.client.MongoClient
Kotlin Coroutine driverCoroutine-based server-side Kotlin code.mongodb-driver-kotlin-coroutinecom.mongodb.kotlin.client.coroutine.MongoClient
Legacy Java driverOlder Kotlin code that already uses Java driver classes.mongo-java-drivercom.mongodb.MongoClient

1. Download MongoDB Java Driver or add Kotlin driver dependency

Download latest available MongoDB Java Driver from Maven Repository.
https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver/
For this tutorial, we shall download 3.5.0, which was then latest.

The older mongo-java-driver dependency works with the legacy example shown below. For a new Kotlin application, prefer the official Kotlin driver dependency.

Gradle Kotlin DSL for Kotlin Sync driver

</>
Copy
dependencies {
    implementation(platform("org.mongodb:mongodb-driver-bom:5.8.0"))
    implementation("org.mongodb:mongodb-driver-kotlin-sync")
}

Gradle Kotlin DSL for Kotlin Coroutine driver

</>
Copy
dependencies {
    implementation(platform("org.mongodb:mongodb-driver-bom:5.8.0"))
    implementation("org.mongodb:mongodb-driver-kotlin-coroutine")
}

2. Add jar file to the Kotlin build path

In IntelliJ IDEA, copy the jar file to lib folder, then right click on the jar file and ‘Add as Library’.

In Eclipse, follow the navigation path: Project -> Properties -> Java Build Path -> Libraries -> Add Jars -> Select the jar -> Click “Apply” -> Click “OK”

If you use Gradle or Maven, do not add the JAR manually. Add the dependency, reload the project, and let the build tool download the driver.

3. Create MongoClient in Kotlin

In your Kotlin Application, create a new MongoClient with host and port provided as arguments to the constructor.

</>
Copy
mongoClient = MongoClient( host , port )

host (String) and port (Integer) are IP Address or hostname and Port Number respectively at which MongoDB Daemon Service is running.
If the details provided are successful, mongoClient creates a new Client to the MongoDB.

In the current Kotlin Sync driver, create the client from a MongoDB URI.

</>
Copy
val uri = "mongodb://localhost:27017/"
val mongoClient = MongoClient.create(uri)

For MongoDB Atlas, the URI usually starts with mongodb+srv://.

</>
Copy
val uri = "mongodb+srv://<db_username>:<db_password>@<cluster-host>/?retryWrites=true&w=majority"
val mongoClient = MongoClient.create(uri)

4. Verify Kotlin MongoDB connection with ping

If there is no exception thrown during MongoClient creation, your MongoClient is successfully connected to MongoDB.

In current driver code, run a simple ping command after creating the client. This confirms that the Kotlin application can reach MongoDB and that the connection string is valid.

</>
Copy
mongoClient.getDatabase("admin").runCommand(Document("ping", 1))
println("Connected to MongoDB!")

5. Close connection to MongoDB

Once you are done with the MongoDB Operations, close the connection between MongoClient and MongoDB Daemon Service.

</>
Copy
mongoClient!!.close()

For new Kotlin code, avoid force-unwrapping with !! unless the value is guaranteed to be non-null. Prefer closing the client in a finally block, or reuse one client for the lifetime of a server application.

Example – Connection to MongoDB using Kotlin

In this example Kotlin Program, we will establish a connection to MongoDB by creating a MongoClient object.

</>
Copy
import com.mongodb.MongoClient
import com.mongodb.MongoException

/**
 * Created by TutorialKart on 31/10/17.
 */
object KotlinMongoConnectionExample {
    @JvmStatic
    fun main(args: Array<String>) {
        var mongoClient: MongoClient? = null
        try {
            mongoClient = MongoClient("127.0.0.1", 27017)
            println("Connected to MongoDB!")
        } catch (e: MongoException) {
            e.printStackTrace()
        } finally {
            mongoClient!!.close()
        }
    }
}

Output

Nov 01, 2017 9:08:55 AM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Connected to MongoDB!

Modern Kotlin Sync driver example for local MongoDB

</>
Copy
import com.mongodb.kotlin.client.MongoClient
import org.bson.Document

fun main() {
    val mongoClient = MongoClient.create("mongodb://localhost:27017/")

    try {
        mongoClient.getDatabase("admin").runCommand(Document("ping", 1))
        println("Connected to MongoDB from Kotlin!")
    } catch (e: Exception) {
        println("Could not connect to MongoDB: ${e.message}")
    } finally {
        mongoClient.close()
    }
}

Output

Connected to MongoDB from Kotlin!

Kotlin Coroutine driver example for MongoDB connection

</>
Copy
import com.mongodb.MongoException
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.BsonInt32
import org.bson.Document

fun main() = runBlocking {
    val mongoClient = MongoClient.create("mongodb://localhost:27017/")

    try {
        val command = Document("ping", BsonInt32(1))
        mongoClient.getDatabase("admin").runCommand(command)
        println("Connected to MongoDB using Kotlin coroutines!")
    } catch (e: MongoException) {
        println("Could not connect to MongoDB: ${e.message}")
    } finally {
        mongoClient.close()
    }
}

Connect Kotlin application to MongoDB Atlas

To connect Kotlin to MongoDB Atlas, copy the mongodb+srv connection string from your Atlas cluster, replace the placeholders, and make sure the application IP address is allowed in Atlas Network Access.

</>
Copy
import com.mongodb.kotlin.client.MongoClient
import org.bson.Document

fun main() {
    val username = System.getenv("MONGODB_USERNAME")
    val password = System.getenv("MONGODB_PASSWORD")
    val clusterHost = System.getenv("MONGODB_CLUSTER_HOST")

    val uri = "mongodb+srv://$username:$password@$clusterHost/?retryWrites=true&w=majority"
    val mongoClient = MongoClient.create(uri)

    try {
        mongoClient.getDatabase("admin").runCommand(Document("ping", 1))
        println("Connected to MongoDB Atlas from Kotlin!")
    } finally {
        mongoClient.close()
    }
}

If the password contains special characters, encode it correctly for use in a URI. Do not hard-code production credentials in Kotlin source files.

Access MongoDB database and collection from Kotlin

</>
Copy
import com.mongodb.kotlin.client.MongoClient
import org.bson.Document

fun main() {
    val mongoClient = MongoClient.create("mongodb://localhost:27017/")

    try {
        val database = mongoClient.getDatabase("school")
        val students = database.getCollection<Document>("students")

        val student = Document("name", "Arun")
            .append("class", 10)
            .append("subject", "Mathematics")

        students.insertOne(student)
        println("Document inserted successfully.")
    } finally {
        mongoClient.close()
    }
}
Document inserted successfully.

Common Kotlin MongoDB connection errors and fixes

Error or symptomLikely reasonWhat to check
Connection refusedMongoDB is not running or the port is wrong.Start MongoDB and check localhost:27017.
Authentication failedWrong username, password, authentication database, or permissions.Verify the database user and roles.
Atlas connection times outIP address is not allowed or the network blocks the connection.Check Atlas Network Access and firewall rules.
Unresolved reference: MongoClientWrong dependency or import.Use the import that matches your selected driver.
Client is created but connection is not provenNo server command has been executed yet.Run ping after creating the client.

Security notes for Kotlin MongoDB connection strings

  • Do not commit MongoDB usernames, passwords, or Atlas cluster strings to Git.
  • Read credentials from environment variables or a secure configuration provider.
  • Use a database user with only the permissions required by the application.
  • For Atlas, keep IP access rules as narrow as practical.
  • Use TLS-enabled connection strings for production deployments where required.

QA checklist for Kotlin MongoDB connection tutorial

  • Confirm that legacy Java driver code and current Kotlin driver code are clearly separated.
  • Check that Kotlin Sync examples import com.mongodb.kotlin.client.MongoClient.
  • Check that coroutine examples import com.mongodb.kotlin.client.coroutine.MongoClient.
  • Verify that sample connection strings do not contain real credentials.
  • Run local examples only after MongoDB is running on localhost:27017.
  • For Atlas examples, check network access and database user permissions.

FAQs on connecting MongoDB from Kotlin application

How do I connect a Kotlin application to MongoDB?

Add the MongoDB Kotlin driver dependency, create a MongoClient with a connection string, and run a command such as ping. For local MongoDB, use mongodb://localhost:27017/.

Should I use Kotlin Sync driver or Kotlin Coroutine driver?

Use the Kotlin Sync driver for blocking code. Use the Kotlin Coroutine driver when your application uses coroutines or suspend-based workflows.

Can I use MongoDB Java driver from Kotlin?

Yes. Kotlin can call Java driver classes, and older projects may use com.mongodb.MongoClient. For new Kotlin projects, use the Kotlin Sync or Coroutine driver.

How do I verify that Kotlin is connected to MongoDB?

Run mongoClient.getDatabase("admin").runCommand(Document("ping", 1)). If the command succeeds, the application can reach MongoDB.

How do I connect Kotlin to MongoDB Atlas?

Copy the Atlas mongodb+srv connection string, replace the placeholders, allow your application IP address, and create the client using MongoClient.create(uri).

References for Kotlin MongoDB driver setup

  1. Java Programming Tutorial
  2. MongoDB Kotlin Sync Driver – Connect to MongoDB
  3. MongoDB Kotlin Coroutine Driver – Connect to MongoDB
  4. MongoDB Kotlin Driver Quick Start Examples

Conclusion

In this MongoDB Tutorial, we have learnt to make a connection to MongoDB from Kotlin Application using MongoDB Java Driver.

For new Kotlin applications, add the Kotlin Sync driver or Kotlin Coroutine driver, create the client with MongoClient.create(uri), verify the connection with ping, and close or reuse the client based on your application design.