For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Migrate from KMongo

This page contains a high-level comparison of most of the ways the official MongoDB Kotlin Driver and the community-developed KMongo driver differ. You can use this page to identify the changes you need to make to migrate from the deprecated KMongo driver to the official MongoDB Kotlin Driver.

KMongo is a popular community-developed library for working with MongoDB from Kotlin applications. It is a wrapper around the Java driver that was created prior to the creation of the official Kotlin driver to serve the needs of the Kotlin community.

Important

As of July 2023, KMongo has been marked as deprecated.

The MongoDB Kotlin Driver is the officially supported and maintained MongoDB driver for Kotlin. It is developed by the MongoDB team.

Although both drivers support synchronous and asynchronous operations, the examples on this page will use asynchronous coroutine-based operations.

The Kotlin driver is the official MongoDB driver for Kotlin. It is developed by the MongoDB team and provides a native API for Kotlin applications to connect to MongoDB and work with data. It is implemented by wrapping the MongoDB Java driver.

KMongo is a popular community-developed library for working with MongoDB from Kotlin applications. It is a wrapper around the Java driver that was created prior to the creation of the official Kotlin driver to serve the needs of the Kotlin community.

Important

As of July 2023, KMongo has been marked as deprecated.

The Kotlin driver was developed in collaboration with the creator of KMongo, Julien Buret, to give users an officially-supported driver.

The official Kotlin driver and KMongo have generally similar APIs. Notable similarities between the Kotlin driver and KMongo include:

  • Support for synchronous and coroutine-based operations

  • Support using data classes to represent MongoDB documents

  • Support for KotlinX serialization

  • Support for MongoDB CRUD API and aggregation API

Although the official Kotlin driver and KMongo are similar, there are some key differences:

  • The official driver does not have built-in support for reactor, rxjava2, Jackson, or GSON.

  • The official driver does not support MongoDB shell commands.

Both drivers let you connect to and communicate with MongoDB clusters from a Kotlin application.

To connect to a MongoDB cluster using the MongoDB Kotlin Driver:

import com.mongodb.kotlin.client.coroutine.MongoClient
data class Jedi(val name: String, val age: Int)
// Replace the placeholder with your MongoDB deployment's connection string
val uri = CONNECTION_STRING_URI_PLACEHOLDER
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("test")
// Get a collection of documents of type Jedi
val collection = database.getCollection<Jedi>("jedi")

See the Connect to MongoDB documentation for more information.

Both drivers provide support for all MongoDB CRUD APIs and aggregation operations.

Tip

If you are accustomed to constructing query filters by using the infix notation available in KMongo, you can also use this notation to create filters in the official Kotlin driver by using extension methods from the mongodb-driver-kotlin-extensions package. Select the Kotlin Driver Extensions tab to view an example that uses this query syntax in the Kotlin driver.

The MongoDB Kotlin Driver also provides functions for all basic CRUD operations:

// Insert a document
val jedi = Jedi("Luke Skywalker", 19)
collection.insertOne(jedi)
// Find a document
val luke = collection.find(Jedi::name.name, "Luke Skywalker")
val jedis = collection.find(lt(Jedi::age.name, 30)).toList()
// Update a document
val filter = Filters.eq(Jedi::name.name, "Luke Skywalker")
val update = Updates.set(Jedi::age.name, 20)
collection.updateOne(filter, update)
// Delete a document
val filter = Filters.eq(Jedi::name.name, "Luke Skywalker")
collection.deleteOne(filter)

You can build aggregation pipelines by using the aggregate() method and the pipeline function:

data class Results(val avgAge: Double)
val resultsFlow = collection.aggregate<Results>(
listOf(
Aggregates.match(Filters.ne(Jedi::name.name, "Luke Skywalker")),
Aggregates.group("\$${Jedi::name.name}",
Accumulators.avg("avgAge", "\$${Jedi::age.name}"))
)
)
resultsFlow.collect { println(it) }

See the CRUD Operations and Aggregation documentation for more information.

Both drivers provide support for type-safe queries using property references.

Tip

If you are accustomed to constructing query filters by using the infix notation available in KMongo, you can also use this notation to create filters in the official Kotlin driver by using extension methods from the mongodb-driver-kotlin-extensions package. Select the Kotlin Driver Extensions tab to view an example that uses this query syntax in the Kotlin driver.

The MongoDB Kotlin Driver uses the Builders API to construct queries. Alternatively, you can use the Document class.

data class Person(val name: String, val email: String, val gender: String, val age: Int)
data class Results(val email: String)
val collection = database.getCollection<Person>("people")
// Using Builders
val filter = and(eq("gender", "female"), gt("age", 29))
val projection = fields(excludeId(), include("email"))
val results = collection.find<Results>(filter).projection(projection)
// Using Document class
val filter = Document().append("gender", "female").append("age", Document().append("\$gt", 29))
val projection = Document().append("_id", 0).append("email", 1)
val results = collection.find<Results>(filter).projection(projection)

To map a KMongo string query to the Kotlin driver, you can use the JsonObject class.

val query = JsonObject("{\"name\": \"Gabriel Garc\\u00eda M\\u00e1rquez\"}")
val jsonResult = collection.find(query).firstOrNull()

For more information, see the following Kotlin driver documentation:

Both drivers support the use of Kotlin data classes and the Document class to model the data stored in a MongoDB collection. The Document class lets you model data represented in a MongoDB collection in a flexible format.

You can use data classes and Document classes to model data with the MongoDB Kotlin Driver:

// With data class
data class Movie(val title: String, val year: Int, val rating: Float)
val dataClassCollection = database.getCollection<Movie>("movies")
val movieDataClass = dataClassCollection.findOneOrNull()
val movieNameDataClass = movieDataClass.title
// With Document class
val documentCollection = database.getCollection<Movie>("movies")
val movieDocument = documentCollection.findOneOrNull()
val movieTitleDocument = movieDocument.getString("title")

Both drivers provide support for serializing and deserializing data objects in Kotlin to and from BSON.

You can serialize data classes in the Kotlin driver using both automatic data class codecs and the kotlinx.serialization library. The driver provides an efficient Bson serializer that handles the serialization of Kotlin objects to BSON data.

@Serializable
data class LightSaber(
@SerialName("_id") // Use instead of @BsonId
@Contextual val id: ObjectId?,
val color: String,
val qty: Int,
@SerialName("brand")
val manufacturer: String = "Acme" // Use instead of @BsonProperty
)

To learn more, see the Kotlin Serialization documentation.

If you use the Document class to represent your collection, you can serialize it to JSON and EJSON using the .toJson() method:

val document = Document("_id", 1).append("color", "blue")
// Serialize to JSON
document.toJson()
// Serialize to EJSON
val settings = JsonWriterSettings.builder().outputMode(JsonMode.STRICT).build()
val json = doc.toJson(settings)

To learn more about serializing data with the Document class, refer to Document Data Format - Extended JSON documentation.

Both drivers support synchronous and asynchronous operations.

The MongoDB Kotlin Driver also has separate libraries for synchronous and asynchronous operations. However, the Kotlin driver only has built-in support for coroutines as an asynchronous paradigm. The MongoDB Kotlin Driver does not currently provide support for other asynchronous paradigms such as Reactive Streams, Reactor, or RxJava2.

Driver
Package

Sync

com.mongodb.kotlin.client

Coroutines

com.mongodb.kotlin.client.coroutine

Unlike KMongo, if you want to write asynchronous code, you only need to import the relevant package.

To write synchronous code:

import com.mongodb.kotlin.client.MongoClient
// Instantiate your collection
data class Jedi(val name: String, val age: Int)
val uri = "<your-connection-string">
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("test")
val collection = database.getCollection<Jedi>("jedi")
// Synchronous operations
val jedi = Jedi("Luke Skywalker", 19)
collection.insertOne(jedi)

To write asynchronous coroutine code:

import com.mongodb.kotlin.client.coroutine.MongoClient
// Instantiate your collection
data class Jedi(val name: String, val age: Int)
val uri = "<your-connection-string">
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("test")
val collection = database.getCollection<Jedi>("jedi")
runBlocking {
// Async operations
val jedi = Jedi("Luke Skywalker", 19)
collection.insertOne(jedi)
}

Now that you have learned about the differences between KMongo and the MongoDB Kotlin driver, see the Quick Start to get started using the KMongo Kotlin driver.