Sling Academy
Home/Kotlin/Performing CRUD Operations in MongoDB with Kotlin

Performing CRUD Operations in MongoDB with Kotlin

Last updated: November 30, 2024

In this article, we will explore how to perform CRUD (Create, Read, Update, Delete) operations in MongoDB using Kotlin. MongoDB is a NoSQL database that works well with Kotlin due to its flexibility and scalability. By integrating these two technologies, you can create robust applications efficiently.

Setting Up the Environment

First, ensure you have the necessary setup before diving into coding:

  • Install MongoDB Community Server. Follow the instructions for your operating system.
  • Include MongoDB driver for Kotlin in your build.gradle.kts file:

dependencies {
    implementation("org.mongodb:mongodb-driver-sync:4.9.0")
}

Connecting to MongoDB

To connect to MongoDB, you need to create a new client as shown below:


import com.mongodb.client.MongoClients

val client = MongoClients.create("mongodb://localhost:27017")
val database = client.getDatabase("testdb")
val collection = database.getCollection("testCollection")

Create Operation

You can insert documents into your MongoDB collection using the following method:


import org.bson.Document

val document = Document("name", "John")
    .append("age", 30)
    .append("occupation", "Engineer")
collection.insertOne(document)

Read Operation

To retrieve documents, you can find data in a variety of ways. Here's a simple example of fetching all the documents from a collection:


val findIterable = collection.find()
findIterable.forEach { println(it.toJson()) }

Update Operation

To update documents in the collection, use the following approach:


val updateResult = collection.updateOne(
    Document("name", "John"),
    Document("$set", Document("age", 31))
)
println("Modified count: " + updateResult.modifiedCount)

Delete Operation

Deleting documents can be performed using the delete operations provided by MongoDB:


val deleteResult = collection.deleteOne(Document("name", "John"))
println("Deleted count: " + deleteResult.deletedCount)

Conclusion

In this article, you've learned how to perform basic CRUD operations with MongoDB using Kotlin. Whether you’re developing a new application or working on an existing project, the MongoDB-Kotlin integration is powerful and provides great flexibility.

Next Article: Querying MongoDB Collections Programmatically with Kotlin

Previous Article: Connecting to MongoDB with Kotlin Using `KMongo`

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