How to Insert a MongoDB Document using Kotlin

Introduction

If you’re using the Kotlin programming language to build apps, you may want your applications to have the ability to insert documents into MongoDB. Fortunately, that task is a simple one to accomplish. In this tutorial, we’ll provide instructions and code examples to show you how to insert a MongoDB document using Kotlin.

Prerequisite

Before we proceed with our tutorial, let’s review a couple of prerequisites that are necessary for this project:

  • MongoDB server must be installed and configured on your system.
  • The Eclipse application also needs to be installed and configured.

Install Kotlin in Eclipse

In this section, we’ll explain how to install the Kotlin plugin in Eclipse. This plugin will enable us to access our Kotlin application using the Eclipse IDE. We’ll need to perform the following steps:

  1. First, we’ll start the Eclipse IDE by double-clicking or right-clicking on the Eclipse icon, then selecting Open.

  2. Next, we’ll find the Help button in the menu bar. After clicking on it, we’ll select Eclipse Marketplace in its sub-menu.

alt text

  1. In the search bar, we’ll type Kotlin, then press Enter on the keyboard.

  2. Then we’ll select ‘Kotlin Plugin for Eclipse 0.8.19’.

  3. Finally, we will click the Install Now > button to move forward with the installation of the Kotlin plugin.

Downloading MongoDB Java Driver

We’ll need a driver to allow our Kotlin application to connect to a MongoDB server, so our next step will be to download the MongoDB Java Driver, which is a JAR file.

NOTE: The latest version of the MongoDB Java Driver is 3.12.

Adding JAR file to ECLIPSE build path

In the previous section, we downloaded the JAR file that we’ll need for the MongoDB Java Driver. Now we’ll add that JAR file to our Eclipse application so that we can use it.

Let’s review the steps needed to accomplish this task:

  1. First, select the Project in the menu bar.
  2. Then select the Properties.
  3. After that, click on Java Build Path
  4. Select the Libraries tab.
  5. On the right-hand panel, locate the Add External JAR… button and click it.
  6. We’ll be selecting the MongoDB Java Driver that we downloaded in the previous section. Its name should look something like: mongo-java-driver-3.12.0
  7. Finally, click the Apply and Close button to add the JAR file to the Eclipse application.

Creating a Kotlin Project

Now that we’ve added the required JAR to our Eclipse application, we’re ready to create a Kotlin project. We can connect the project to a MongoDB server and perform an INSERT operation within our code.

We’ll need to perform the following steps:

  1. First, we’ll click on File in the menu bar.
  2. Then we’ll select New
  3. After that, we’ll select Kotlin Project
  4. In the Project Name text box, we need to provide a meaningful name for the project. For this tutorial, we will name the project kotlinmongo.

Create a Kotlin Object File

At this point, we have our Kotlin project set up, so we can now create a Kotlin object. This is where we can add the code that will connect to an existing MongoDB server.

To do this, we’ll need to perform the following steps:

  • Right-click the Kotlin project that we created earlier. In our example, the name of the project was kotlinmongo.
  • Select New
  • Then select Kotlin Object
  • We’ll need to provide a meaningful name for the Kotlin Object, so let’s name it KotlinMongoInsert.
  • Finally, we click the Finish button to create the Kotlin file.

Coding the Kotlin MongoDB Insert Operation

Next, we’re going to write the code that will allow Kotlin to connect to MongoDB. Let’s open up the KotlinMongoInsert.kt file and add the code shown below:

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

object KotlinMongoInsert {
    @JvmStatic
    fun main(args: Array<String>){
        var mongoClient: MongoClient? = null
        try {
            mongoClient = MongoClient("127.0.0.1", 27017)
            var db = mongoClient.getDB("testDB")
            var tbl = db.getCollection("user")
           

            val document = BasicDBObject()
            document.put("name","dwane")
            document.put("lastname","holmes")
            tbl.insert(document)
           
           
        } catch (e: MongoException) {
            e.printStackTrace()
        } finally {
            mongoClient!!.close()
        }
    }
   
    data class User(val name: String, val lastname: String)
}

There’s quite a bit going on in this code, so let’s take a closer look at it:

  • First, we used the @JvmStatic annotation. This tells the compiler to generate an additional method. For more information on this, consult Kotlin’s documentation here.

  • Next, we use fun main(args: Array<String>) as the application’s entry point. This is what makes the application executable.

  • We then create a MongoClient, passing the host and port to the constructor as arguments. The host indicates the hostname of the machine where the MongoDB service is running, and the port indicates where the service is listening for connections.

  • We create a document and assign it to a variable named ‘tbl’.

  • Then we perform an insert operation using the tbl.insert() method with our document as argument.

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

We can see if our INSERT operation was successful using the MongoDB shell:

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
testDB  0.000GB
> use testDB
switched to db testDB
> show collections
user
> db.user.find().pretty()
{
        "_id" : ObjectId("5e09663da9bed87af4b676b8"),
        "name" : "dwane",
        "lastname" : "holmes"
}
>

Conclusion

If you plan to make use of MongoDB in your Kotlin applications, it’s important to know how to perform common database operations from your code. In this article, we focused on the MongoDB insert operation, and we showed how to insert a MongoDB document using Kotlin. With our code examples to guide you, you’ll be able to add MongoDB insert functionality to your own Kotlin applications.

The Code

Shown below is the Kotlin code that we used as an example in this tutorial:

The KotlinMongoInsert.kt

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

object KotlinMongoInsert {
    @JvmStatic
    fun main(args: Array<String>){
        var mongoClient: MongoClient? = null
        try {
            mongoClient = MongoClient("127.0.0.1", 27017)
            var db = mongoClient.getDB("testDB")
            var tbl = db.getCollection("user")
           

            val document = BasicDBObject()
            document.put("name","dwane")
            document.put("lastname","holmes")
            tbl.insert(document)
           
       
           
           
        } catch (e: MongoException) {
            e.printStackTrace()
        } finally {
            mongoClient!!.close()
        }
    }
   
    data class User(val name: String, val lastname: String)
}

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.