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. [https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver/] For this tutorial, we shall download 3.5.0, which was then latest.

ADVERTISEMENT

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.

mongoClient!!.close()

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 {
    @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!

Conclusion

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