EventJoin us at AWS re:Invent 2024! Learn how to use MongoDB for AI use cases. Learn more >>

Kotlin and MongoDB

In this tutorial, we'll cover why the Kotlin programming language and MongoDB work well together. We'll provide some examples on getting started with this new programming language, using data classes and coroutines, and more.

A purple chair, desktop on a white table inside a green two-story building surrounded by clouds and purple trees.


Table Contents

What is Kotlin?

Kotlin is a modern cross-platform, statically typed programming language that addresses some common issues in Java while also being fully interoperable with Java and compatible with the JVM, or the Java Virtual Machine. As a programming language, Kotlin has several advantages over Java, including built-in null safety, data classes, and coroutines.

Though one of the primary use cases of Kotlin is mobile development for Android apps, there is a growing community of Kotlin users who are using the language for server-side development as well.

https://mongodb.prakticum-team.ru/proxy/webimages.mongodb.com/_com_assets/cms/liyza1i10ayp6vpvz-document-model.png?auto=format%252Ccompress

What is MongoDB?

MongoDB holds the top spot as the most popular NoSQL database technology on several lists. It is a document database used to build highly available and scalable internet applications. Founded in 2007, MongoDB has a worldwide following in the developer community. MongoDB has always focused on providing developers with an excellent user experience, which, in addition to all its other features, has made MongoDB a favorite of developers worldwide.

If you're building something new and need a database, consider using MongoDB Atlas from the outset. Atlas will give you a fully-managed, cloud-native database service that comes with a number of features, including full-text search, charts, partner integrations, and much more. You can even build web applications on GraphQL directly on top of MongoDB Atlas.

Why use Kotlin and MongoDB together?

MongoDB is a great fit for server-side development using Kotlin. MongoDB has an official server-side Kotlin driver that was made generally available in June 2023. The MongoDB Kotlin driver provides a complete library for building Kotlin applications in an idiomatic way, including first class support for synchronous development and asynchronous programming with Kotlin coroutines and the Kotlinx.serialization library.

MongoDB Atlas

If you don't already have an Atlas account, sign up now! You can create a free-tier MongoDB cluster, create a database collection, load sample datasets, and interact with the data by following our guide. MongoDB Atlas saves time by making it easier to manage database infrastructure. It also has a perpetual free tier for small database and offers reasonable consumption-based pricing for more advanced configurations. No need to have MongoDB installed locally.

Getting Started with MongoDB Atlas

To use the MongoDB Kotlin Driver for server-side, you'll need to have Kotlin installed. You'll also need to create a MongoDB cluster to store and manage the data that you'll be using in your application. Complete the Get Started with Atlas guide to set up a new Atlas account, create and launch a free tier MongoDB cluster, load sample datasets, and interact with the data.

After completing the steps in the Atlas guide, you should have a new MongoDB cluster deployed in Atlas, a new database user, and sample datasets loaded into your cluster.

The MongoDB Kotlin driver uses a connection string to connect to your MongoDB cluster. This string includes information on the hostname or IP address and port of your cluster, authentication mechanism, user credentials when applicable, and other connection options.

To retrieve your connection string for use with the Kotlin driver, navigate to the Database section of your Atlas account and click Connect for the cluster that you want to connect to. You'll be prompted to select your driver and version, and you'll then be able to copy your connection string. Remember to substitute in your own username and password in the string!

Using the Kotlin Driver in Your Application


Adding A Dependency on the Kotlin Driver

To easily configure Gradle or Maven to build and run your project, we recommend you use an IDE like IntelliJ IDEA or Eclipse. You'll want to add MongoDB as a dependency. You can find more instructions on how to add a dependency on the MongoDB Kotlin driver here.


Querying MongoDB from Your Application

You should already have a sample dataset loaded into your MongoDB cluster from an earlier step (see: Getting Started with MongoDB Atlas for further instructions) and easy access to your connection string.

To query your MongoDB cluster from your application, you'll need to create a data class that represents a MongoDB document and to write a main function that includes information on your cluster's URI. A full tutorial and sample code can be found here.

Kotlin Driver Fundamentals

Two documents, one orange and one green, are behind a search window. A magnifying glass hovers over the search window.

CRUD Operations

CRUD (Create, Read, Update, Delete) operations enable you to work with data stored in MongoDB. You can consider these operations in two categories: Read and Write.

Read operations find and return documents stored in your database. Some examples of read operations are:

Write operations allow you to make changes to the information stored in your database. Some examples of write operations are:

To reduce the number of calls to the database, you can also use bulk operations. To learn more about bulk operations, consult the documentation. The documentation also has sample code snippets to help you get started.


Kotlin Data Classes

True to their name, data classes in Kotlin are classes whose main property is to hold data. The compiler automatically derives several members based on the properties declared in the class's constructor. These members include equals() and hashCode(), toString(), and more.

The Kotlin server-side driver natively supports encoding and decoding Kotlin data classes for MongoDB read and write operations using the default codec registry (a collection of classes that define how to encode and decode both Java and Kotlin types).

You can insert and retrieve a data class, as well as configure the serialization behavior of data classes using the Kotlin driver. You can find more information on data class support in the Kotlin driver here.

Resources For Further Learning

To find the server-side Kotlin driver syntax and code snippets for several common MongoDB commands and links to their related reference and API documentation, consult the Quick Reference in the Kotlin driver documentation.

To dive deeper into MongoDB core concepts, check out MongoDB University! It comes with self-paced video lessons, on-demand labs, certifications with digital badges, and more. For Kotlin-specific code examples and written tutorials, try the MongoDB Developer Center.

If you're new to Kotlin, consider exploring the Kotlin documentation or checking out some Kotlin tutorials on freeCodeCamp.

Getting Help

The best part of using MongoDB is the vibrant developer community that includes users with all levels of experience with the Kotlin server-side driver and Kotlin Realm SDK. The best way to get support for general questions is to use MongoDB Community Forums.

FAQs

How is the Kotlin server-side driver different from KMongo?

KMongo is an unofficial, community-created driver that was built to address the need for Kotlin server-side support with MongoDB. The official MongoDB server-side driver is similar to KMongo in that both rely on the MongoDB Java driver "under the hood", but only the MongoDB server-side Kotlin driver comes with official support and maintenance.

What's the difference between Kotlin for server-side and Kotlin for mobile development?

One of the most popular use cases for Kotlin is Android development. Since 2019, Android mobile development has been Kotlin-first. However, close to half of all Kotlin developers are using the language for server-side. Kotlin is a great fit for server-side applications due to its scalability, interoperability with Java-based frameworks, and its tooling. Kotlin even offers framework-specific tooling in the plugin for IntelliJ IDEA Ultimate.

How is Kotlin different from Java?

Java and Kotlin are both powerful programming languages that run on the Java Virtual Machine (JVM), but there are differences between the two.

Kotlin is a new language meant to solve a few problems common in Java, and comes with function types, coroutines, and built-in null safety, as well as a more concise syntax resulting in fewer lines of code. It supports both object oriented programming and functional programming. However, Java is significantly more established and boasts a wider pool of developers who know the language.

The two languages are interoperable, which means that you can call Kotlin code from Java code, and vice-versa.

What is a Kotlin coroutine? Do I need to use them?

Coroutines in Kotlin are similar to lightweight threads, but actually less resource-intensive than JVM threads as per the official Kotlin documentation. Coroutines allow for asynchronous programming, and in the case of server-side, can enable scaling to massive numbers of clients. If your application is synchronous, you do not need coroutines -- and in fact, you can use the Kotlin sync driver. However, if your application is asynchronous, you can use the Kotlin driver with coroutine support.

Is MongoDB a good fit for my Kotlin application?

If you're developing a server-side application that uses Kotlin, MongoDB is a great fit. Consider the official MongoDB Kotlin driver. It comes with support for both synchronous use cases and asynchronous use cases with Kotlin coroutines.

Where is the API documentation?

The API documentation for the server-side driver can be found here. This includes documentation for both the Kotlin coroutine and Kotlin sync driver, as well as Core (essential driver functionality) and BSON kotlinx.serialization.

Can I contribute to the Kotlin driver?

We're happy to accept contributions to help improve the Kotlin driver. We will guide user contributions to ensure they meet the standards of the Kotlin driver codebase. Please ensure that any PRs include documentation, tests, and pass checks. The source code for the Kotlin driver can be found here.