Connect to MongoDB from Kotlin

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

To connect to MongoDB from Kotlin Application, following is a 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 : 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.

    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 Kotlin Program – To demonstrate Connection to MongoDB

Following is an example Kotlin Program to demonstrate on how to establish a connection to MongoDB by creating a MongoClient :

Conclusion :

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