Connect to MongoDB from Kotlin

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

To connect to MongoDB from Kotlin Application, follow this step by step guide.

1. Download MongoDB Java Driver

Download latest available MongoDB Java Driver from Maven Repository. [] For this tutorial, we shall download 3.5.0, which was then latest.


2. Add jar file to the 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”

3. Create MongoClient

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

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.

4. MongoClient is Ready

If there is no exception thrown during MongoClient creation, your MongoClient is successfully 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.


Example – Connection to MongoDB using Kotlin

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

import com.mongodb.MongoClient
import com.mongodb.MongoException

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


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


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