Sling Academy
Home/Kotlin/Connecting to MongoDB with Kotlin Using `KMongo`

Connecting to MongoDB with Kotlin Using `KMongo`

Last updated: November 30, 2024

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.

Next Article: Performing CRUD Operations in MongoDB with Kotlin

Previous Article: Introduction to MongoDB in Kotlin Projects

Series: Kotlin - Interacting with Databases

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin