Introduction

In this article, we will explore how to connect to MongoDB using Kotlin with the help of the KMongo library. KMongo is a MongoDB driver tailored for Kotlin, providing a natural Kotlin-like API to interact with MongoDB.

Prerequisites

  • Basic knowledge of Kotlin.
  • Access to a MongoDB server.
  • IntelliJ IDEA or another Kotlin-compatible IDE.

Setting Up Your Kotlin Project

First, create a new Kotlin project in your preferred IDE. In this example, we will use Gradle as the build tool.

Step 1: Add KMongo Dependency

Include the KMongo dependency in your build.gradle.kts file:


dependencies {
    implementation("org.litote.kmongo:kmongo:4.5.0")
}

Ensure you sync your project to download the dependency.

Connecting to MongoDB

Once your project is set up, you can proceed with establishing a connection to your MongoDB server. Below is a simple example to demonstrate this.

Step 2: Establish Connection

Create a Kotlin file named Main.kt and set up the connection:


import org.litote.kmongo.*

fun main() {
    // Connect to the MongoDB server
    val client = KMongo.createClient() // use 'mongodb://localhost' to specify the address
    val database = client.getDatabase("myDatabase")
    println("Connected to MongoDB!")
}

This snippet connects to the default MongoDB server running on localhost:27017 and accesses the "myDatabase" database.

Step 3: Insert a Document

Let's insert a document into a collection in our database:


data class Person(val name: String, val age: Int)

fun main() {
    val client = KMongo.createClient()
    val database = client.getDatabase("myDatabase")
    val col = database.getCollection()
    
    // Insert a person object
    col.insertOne(Person("John Doe", 30))
    println("Document inserted!")
}

In this code, we defined a Person data class and inserted an instance of Person into the collection.

Querying the Database

After inserting documents, you may want to query them.


fun main() {
    val client = KMongo.createClient()
    val database = client.getDatabase("myDatabase")
    val col = database.getCollection()
    
    // Query for a document
    val foundPerson = col.findOne(Person::name eq "John Doe")
    if (foundPerson != null) {
        println("Found person: Name = ${foundPerson.name}, Age = ${foundPerson.age}")
    } else {
        println("No person found")
    }
}

This example uses a simple equality filter to query the collection.

Conclusion

Using KMongo library with Kotlin makes it easy and efficient to interact with MongoDB. Feel free to explore more features offered by KMongo to fully leverage its capabilities in your Kotlin applications.