Connecting Kotlin and MongoDB

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

If you’re working with the Kotlin programming language and you want your apps to interact with a MongoDB database, you’ll need to create the right connections between these two technologies. Fortunately, it only requires a few simple steps to accomplish this task. In this article, we’ll walk you through the process of connecting Kotlin and MongoDB, and we’ll provide some sample code to help you get started.

Prerequisite

Before proceeding with the steps outlined in this article, make sure that the following software has been installed and configured:

You’ll need to download the MongoDB driver in order to connect Kotlin to a MongoDB database. Download it here.

Installing Kotlin in Eclipse IDE

Our first task will be to install Kotlin in the Eclipse IDE. We’ll perform the following steps:

  • First, locate the Eclipse Market Place, which can be found under the Help button.
  • In the search box, enter Kotlin.
  • Finally, click the Install button at the lower right corner of the application window.

NOTE: Since we already installed Kotlin, the button’s caption in this screenshot may differ from your own screen:

Creating a Kotlin Project

Next, we’ll create a Kotlin project. The process is fairly simple:

  1. First, click File on the menu bar.
  2. Select the New button.
  3. Then select Kotlin Project
  4. Finally, provide a meaningful name for your project. In this case, we named our project KotlinMongodb.

Adding the JAR File to Kotlin Build Path

We need to add the downloaded JAR file to our Eclipse IDE so that we can access its libraries. Here’s how to do it:

  • Right click on the KotlinMongodb project.
  • Select Build Path, then click Configure Build Path…
  • Go to the Libraries tab.
  • Click on Add External JARs…, then locate the JAR file that we downloaded earlier.
  • Finally, click Apply and Close.

Connecting Kotlin With MongoDB

At this point, we’re ready to create a Kotlin object and code our basic application that will connect to MongoDB.

Create Kotlin Object File

Here’s how we’ll create the Kotlin object file that will hold our code:

  • First, right-click the Kotlin project, then select New.
  • Click on Kotlin Object, then provide a name for the object.

  • Finally, click the Finish button.

Coding the Kotlin and MongoDB Connection

Shown below is the Kotlin code we’ll need for our MongoDB connection. We’ll add this code to the KotlinConnection.kt file. It may seem like there’s a lot going on in this code, but we’ll review it in greater detail below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import com.mongodb.MongoClient
import com.mongodb.MongoException

object KotlinConnection {
    @JvmStatic
    fun main(args: Array<String>){
        var mongoClient: MongoClient? = null
        try{
            mongoClient = MongoClient("127.0.0.1", 27017)
            println("Successfully connected Kotlin to MongoDB!")
        }catch (e: MongoException){
            e.printStackTrace()
        }finally{
            mongoClient!!.close()
        }
    }
}

Let’s take a closer look at this code and discuss what’s happening in it:

  • The use of @JvmStatic instructs the compiler to generate additional methods as required.

  • We declare the application’s entry point using the code fun main(args Array<String>).

  • We then provide details, such as host and port number, relating to our MongoDB server to the MongoClient.

  • We also provide some basic error handling using the try catch block of code.

  • Finally, we close the MongoDB service using mongoClient!!.close()

If we run the Kotlin application, we should see something like the following:

1
2
3
Apr 11, 2020 10:17:00 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}
Successfully connected Kotlin to MongoDB!

Conclusion

If you’re a Kotlin developer who would like to work with MongoDB in their applications, you’ll need to know how to make the necessary connections. In this article, we explained the process of connecting Kotlin and MongoDB, with detailed instructions and code examples. Using this tutorial as a guide, you’ll be ready to connect Kotlin with your own MongoDB database.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.