Kotlin exercise 1: Connect to MongoDB -part 1-

3_maldive

After the firts posts on Kotlin, i want to creating something more difficult. And i chose to try a database connection in Kotlin.

In this exercise i chose to connect my little application to a Mongo database. This choice is driven by a book that i started to read in  these days: “MongoDb in action”, because i want to know more about this type of database. So i decided to try to use both new things: kotlin and MongoDB.

This exercise is organized in this way: first part is a java test connection and operations with MongoDB then the same operations are written in Kotlin.

Ok, let’s start with code:

Firt of all create the instance of mongodb client and create te DB:

import com.mongodb.*;

import java.net.UnknownHostException;
import java.util.Date;

/**
 * Created by Claudio on 30/04/16.
 */
public class Main {

    public static void main(String[] args) {

        try {
            MongoClient mongo = new MongoClient( "localhost" , 27017 );

            DB db = mongo.getDB("testDB");

            DBCollection table;
            table = db.getCollection ("clienti");

            //Insert document
            BasicDBObject document = new BasicDBObject();
            document.put("name", "mkyong");
            document.put("age", 30);
            document.put ("createdDate", new Date ( ));
            table.insert(document);

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

            DBCursor cursor = table.find(searchQuery);

            while (cursor.hasNext()) {
                System.out.println(cursor.next());
            }

        } catch (UnknownHostException e) {
            e.printStackTrace ( );
        } catch (MongoException e) {
            e.printStackTrace();
        }
    }

}

this is a little example to show how to:

  • connect to MongoDB (line 14)
  • create or get database (lines 16-19)
  • create a document (lines 22-26)
  • get insered data (lines 29-32)
  • show on standart output the datas (34-35)

The result of running this code is:

Schermata 2016-05-04 alle 21.09.20

The next part is focused on the Kotlin equivalent code.

 

Advertisements

One thought on “Kotlin exercise 1: Connect to MongoDB -part 1-

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