How to Use MongoDB in Ktor ?

Muhammet Ali ILGAZ
4 min readApr 22, 2023

--

Ktor is a lightweight web framework for Kotlin. It’s designed to be easy to use and provides a wide range of features for building web applications. MongoDB is a popular NoSQL database that’s commonly used for storing and managing large volumes of unstructured data. It’s a great choice for web applications that require fast, scalable, and flexible data storage. In this article, we’ll explore how to set up MongoDB in a Ktor backend project and perform CRUD operations on data stored in MongoDB.

1. Install the MongoDB driver in Ktor.

To use MongoDB in Ktor, we’ll need to add the MongoDB driver to our project. We can do this by adding the following dependency to our build.gradle file:

implementation("org.mongodb:mongodb-driver-sync:4.4.3")

2. Configure MongoDB in Ktor application.

Next, we need to configure MongoDB in our Ktor application. We can do this by creating a MongoDatabase instance using the MongoClient class provided by the MongoDB driver.

import com.mongodb.ConnectionString
import com.mongodb.MongoClientSettings
import com.mongodb.client.MongoClients
import org.litote.kmongo.KMongo
import org.litote.kmongo.getCollection

fun Application.module() {
// Create a MongoDB client and database instance
val clientSettings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString("mongodb://localhost:27017"))
.build()
val client = MongoClients.create(clientSettings)
val database = client.getDatabase("myDatabase")

// Register a route to handle MongoDB requests
routing {
// ...
}
}

In this example, we’re creating a MongoClientSettings instance and passing in a MongoDB connection string. We’re also creating a MongoClient instance using the MongoClientSettings instance, and finally, we’re creating a MongoDatabase instance using the MongoClient instance and the name of our database.

Connect to MongoDB in Ktor

Now that we have a MongoDatabase instance, we can use it to connect to MongoDB and perform CRUD operations on our data.

import com.mongodb.client.model.Filters
import com.mongodb.client.model.Updates

suspend fun insertDocument() {
// Connect to the 'myCollection' collection
val collection = database.getCollection<MyData>("myCollection")

// Create a new document to insert
val document = MyData("Ali", "Ilgaz")

// Insert the document into the collection
collection.insertOne(document)
}

We’re connecting to the “myCollection” collection in our MongoDB database using the getCollection() method. We’re then creating a new MyData instance and inserting it into the collection using the insertOne() method.

Create, read, update, and delete data in MongoDB

Once you have successfully connected to MongoDB in your Ktor application, you can perform CRUD (Create, Read, Update, and Delete) operations on your data.

Let’s take a look at how to perform CRUD operations in MongoDB:

Create Data:

To create a new document in MongoDB, you can use the insertOne() method of the MongoCollection object.

Here's an example of how to create a new document:

val collection = database.getCollection<MyDataClass>("myCollection")
val newData = MyDataClass("Ali", 25, "ilgazalii@gmail.com")
collection.insertOne(newData)

In this example, we first retrieve a reference to the collection we want to insert the data into. We then create a new instance of our data class and pass it to the insertOne() method to add it to the collection.

Read Data:

To read data from MongoDB, you can use the find() method of the MongoCollection object.

val collection = database.getCollection<MyDataClass>("myCollection")
val allData = collection.find().toList()

In this example, we retrieve a reference to the collection we want to read data from. We then call the find() method to retrieve all documents in the collection, and use the toList() method to convert the result to a list of our data class.

You can also retrieve a single document by passing a filter to the find() method. For example, to retrieve a document with a specific email address, you can do the following:

val collection = database.getCollection<MyDataClass>("myCollection")
val filter = MyDataClass::email eq "ilgazalii@gmail.com"
val data = collection.find(filter).first()

In this example, we define a filter that matches the document with the email address “ilgazalii@gmail.com”. We then call the find() method with the filter, and use the first() method to retrieve the first matching document.

Update Data:

To update data in MongoDB, you can use the updateOne() method of the MongoCollection object.

val collection = database.getCollection<MyDataClass>("myCollection")
val filter = MyDataClass::name eq "Ali"
val update = MyDataClass::age inc 1
collection.updateOne(filter, update)

In this example, we define a filter that matches the document with the name “Ali”. We then define an update that increments the age field by 1. We then call the updateOne() method with the filter and the update to update the document.

Delete Data:

To delete data from MongoDB, you can use the deleteOne() or deleteMany() methods of the MongoCollection object.

val collection = database.getCollection<MyDataClass>("myCollection")
val filter = MyDataClass::name eq "Ali"
collection.deleteOne(filter)

In this example, we define a filter that matches the document with the name “Ali”. We then call the deleteOne() method with the filter to delete the document.

You can also delete multiple documents by using the deleteMany() method and passing a filter that matches multiple documents.

These are just some examples of how to perform CRUD operations in MongoDB. With these basic operations, you can build more complex queries and data manipulations to suit your needs.

--

--