Kotlin exercise 1: Connect to MongoDB -part 2-


In the first part of this exercise we have seen how connect to a MongoDb with Java. Now that is clear how the connection can be performed, we can try to do the same with Kotlin.
Ok, no waste other time, start coding:

import com.mongodb.BasicDBObject
import com.mongodb.MongoClient
import com.mongodb.MongoException
import java.net.UnknownHostException
import java.util.*

 * Created by Claudio on 01/05/16.
 * This is a main to test mongoDB connection in kotlin

fun main(args: Array<String>) {

        val mongo = MongoClient("localhost", 27017)

        val db = mongo.getDB("testDB")

        val table = db.getCollection("person")

        //Reflection example
        val person = Person("Jon","Doe",20);

        val data = person.javaClass;

        //Insert document
        val document = BasicDBObject()
        document.put("name", "mkyong")
        document.put("age", 30)
        document.put("createdDate", Date())

        /**** Find and display ****/
        val searchQuery = BasicDBObject();
        searchQuery.put("name", "mkyong");

        val cursor = table.find(searchQuery);

        while (cursor.hasNext()) {
    catch (e: UnknownHostException) {
        e.printStackTrace ( );
    } catch (e: MongoException) {


Sorry but the kotlin code isn’t highlighted

How we see the code is similar with Java example and the output is equal:

Schermata 2016-05-04 alle 21.10.01

This code can be converted from Java code with the intellij IDE function called: “Convert java code to kotlin code”. This can be reached from the search tool or vith copy and paste of java code to kotlin file:


For exercise the “Main.kt” code is was written from scratch.

In this little exercice I learned how connect to MongoDb and how code something more difficult to “hello world” in Kotlin.

A little step for mankind, a big step for a developer!



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s