MongoDB driver for Kotlin (synchronous)
Blocking/synchronous driver for MongoDB, using a rich Kotlin DSL.
Configuration
Add a dependency on dev.opensavvy.ktmongo:driver-sync
.
For example, in a Kotlin Multiplatform project:
plugins {
kotlin("multiplatform")
}
kotlin {
jvm()
// …
sourceSets.commonMain.dependencies {
implementation("dev.opensavvy.ktmongo:driver-sync:VERSION-HERE")
}
}
In a Kotlin JVM project:
plugins {
kotlin("jvm")
}
dependencies {
implementation("dev.opensavvy.ktmongo:driver-sync:VERSION-HERE")
}
Basic usage
Once you have obtained an instance of MongoCollection (see platform-specific instructions on how to do this), you can use it to access the database:
class User(
val _id: ObjectId,
val name: String,
val age: Int,
)
collection.findOne {
User::age gte 18
}
collection.update(
filter = {
User::_id eq ObjectId("507f1f77bcf86cd799439011")
},
update = {
User::name set "Bob"
}
)
Blocking/synchronous driver for MongoDB, using a rich Kotlin DSL.
Configuration
Start by declaring a dependency on this module (see the common page for help).
This driver is built on the top of the official Kotlin driver. You can use the official tutorials to get started and learn how to connect to the database.
The most basic option is to connect to your local MongoDB instance running on localhost:27017
, use:
class User(
val _id: ObjectId,
val name: String,
)
val client = MongoClient.create()
val database = client.getDatabase("my_project")
val collection = database.getCollection<User>("users").asKtMongo()
Note the call to asKtMongo()
which is the only difference from the official usage. From then on, all methods from this driver are available on the collection
variable: see MongoCollection.
This means you are able to use KtMongo DSLs within your existing repositories: simply convert into a KtMongo equivalent where you need KtMongo functionality.