MongoDB
suggest changeMongoDB is a document database. You don't store rows in tables. You store BSON documents (binary JSON) in collections. A document can contain nested objects and arrays, and documents in the same collection don't need the same fields. That maps nicely onto Kotlin data classes: a User with a list of roles and an embedded Address goes into one document, with no join table.
MongoDB publishes an official Kotlin driver in two flavors:
mongodb-driver-kotlin-sync: blocking calls, good for scripts, CLI tools and thread-per-request serversmongodb-driver-kotlin-coroutine:suspendfunctions andFlow, good for Ktor and other coroutine-based servers
Both flavors encode Kotlin data classes directly through the bson-kotlin codec. mongodb-driver-kotlin-extensions adds type-safe query builders that use property references like User::age in place of string field names.
// build.gradle.kts
dependencies {
implementation("org.mongodb:mongodb-driver-kotlin-sync:5.13.0")
// or, for coroutines:
// implementation("org.mongodb:mongodb-driver-kotlin-coroutine:5.13.0")
// type-safe Filters/Updates/Sorts using KProperty
implementation("org.mongodb:mongodb-driver-kotlin-extensions:5.13.0")
// the driver logs through SLF4J; use logback or slf4j-simple to see its logs
runtimeOnly("org.slf4j:slf4j-nop:2.0.17")
}
To run the examples you need a server. Docker is the quickest way. The examples in the transactions section need a replica set, so start a single-node one:
docker run -d --name mongo -p 27017:27017 mongo:9 --replSet rs0
docker exec mongo mongosh --quiet --eval "rs.initiate()"
All output below comes from MongoDB 9.0 and driver 5.13.
Connecting, inserting and finding documents
MongoClient.create() takes a connection string. The client keeps a pool of connections to the server and is thread-safe. Create one per application, share it, and close it on shutdown. Databases and collections are created automatically on first write.
The simplest way to work with data is org.bson.Document. It's a Map<String, Any> that keeps insertion order:
import com.mongodb.client.model.Filters
import com.mongodb.kotlin.client.MongoClient
import org.bson.Document
fun main() {
MongoClient.create("mongodb://localhost:27017").use { client ->
val db = client.getDatabase("shop")
val ping = db.runCommand(Document("ping", 1))
println("ping ok: ${ping.getDouble("ok")}")
val products = db.getCollection<Document>("products")
products.drop() // start fresh
val result = products.insertOne(
Document("name", "Keyboard")
.append("price", 49.99)
.append("tags", listOf("usb", "mechanical"))
.append("stock", Document("warehouse", 12).append("store", 3))
)
println("inserted id: ${result.insertedId?.asObjectId()?.value}")
products.insertMany(
listOf(
Document("name", "Mouse").append("price", 19.5).append("tags", listOf("usb", "wireless")),
Document("name", "Monitor").append("price", 189.0).append("tags", listOf("hdmi")),
)
)
println("count: ${products.countDocuments()}")
val keyboard = products.find(Filters.eq("name", "Keyboard")).firstOrNull()
println("name=${keyboard?.getString("name")} price=${keyboard?.getDouble("price")}")
println("warehouse stock=${keyboard?.getEmbedded(listOf("stock", "warehouse"), Int::class.javaObjectType)}")
println(keyboard?.toJson())
products.find(Filters.lt("price", 100.0)).forEach { doc ->
println("cheap: ${doc.getString("name")}")
}
}
}
ping ok: 1.0
inserted id: 6ad3d7981ba992b042618a7a
count: 3
name=Keyboard price=49.99
warehouse stock=12
{"_id": {"$oid": "6ad3d7981ba992b042618a7a"}, "name": "Keyboard", "price": 49.99, "tags": ["usb", "mechanical"], "stock": {"warehouse": 12, "store": 3}}
cheap: Keyboard
cheap: Mouse
Things to notice:
- Every document has an
_idfield, which is the primary key. If you don't set one, the driver generates anObjectId. It's a 12-byte value that starts with a timestamp, so newer ids sort after older ones. find()returns a lazyFindIterable. Nothing is sent to the server until you iterate it withforEach,toList(),first()orfirstOrNull(). Results arrive in batches through a cursor, so iterating over a million documents doesn't load all of them into memory.- In the Kotlin driver,
FindIterableis not a KotlinIterable, sofor (doc in products.find())doesn't compile. UseforEach,map,toList()orcursor(). Filters.eq,Filters.ltand friends build query documents.Filters.lt("price", 100.0)is just{"price": {"$lt": 100.0}}.
Data classes
Working with Document means a lot of casts. Pass a data class to getCollection<T>() and the driver converts between documents and objects for you:
@BsonIdmarks the property stored as_id.@BsonPropertyrenames a field in the database.- Nullable properties and default values work as you'd expect. A field missing in the document falls back to its default, and extra fields in the document are ignored.
import com.mongodb.client.model.Filters
import com.mongodb.client.model.Projections
import com.mongodb.client.model.Sorts
import com.mongodb.kotlin.client.MongoClient
import org.bson.codecs.pojo.annotations.BsonId
import org.bson.codecs.pojo.annotations.BsonProperty
import org.bson.types.ObjectId
data class Address(val city: String, val country: String)
data class User(
@BsonId val id: ObjectId = ObjectId(),
val name: String,
val email: String,
val age: Int,
val roles: List<String> = emptyList(),
val address: Address? = null,
@BsonProperty("is_active") val active: Boolean = true,
)
// a smaller class for projections: only the fields we ask for
data class NameAndAge(val name: String, val age: Int)
fun main() {
MongoClient.create("mongodb://localhost:27017").use { client ->
val users = client.getDatabase("app").getCollection<User>("users")
users.drop()
users.insertMany(
listOf(
User(name = "Alice", email = "alice@example.com", age = 34, roles = listOf("admin", "dev"),
address = Address("Berlin", "DE")),
User(name = "Bob", email = "bob@example.com", age = 27, roles = listOf("dev"),
address = Address("Warsaw", "PL")),
User(name = "Carol", email = "carol@example.com", age = 41, active = false),
User(name = "Dave", email = "dave@example.com", age = 19, roles = listOf("support"),
address = Address("Berlin", "DE")),
)
)
val alice = users.find(Filters.eq(User::name.name, "Alice")).first()
println(alice)
println("-- age >= 25, oldest first")
users.find(Filters.gte("age", 25))
.sort(Sorts.descending("age"))
.forEach { println("${it.name} ${it.age}") }
println("-- devs in Berlin")
users.find(Filters.and(Filters.eq("roles", "dev"), Filters.eq("address.city", "Berlin")))
.forEach { println(it.name) }
println("-- inactive (field stored as is_active)")
users.find(Filters.eq("is_active", false)).forEach { println(it.name) }
println("-- projection into another class, page 2 of size 2")
users.withDocumentClass<NameAndAge>()
.find()
.projection(Projections.fields(Projections.include("name", "age"), Projections.excludeId()))
.sort(Sorts.ascending("name"))
.skip(2)
.limit(2)
.forEach { println(it) }
println("-- distinct cities")
println(users.distinct<String>("address.city").toList())
println("count with roles: ${users.countDocuments(Filters.exists("roles.0"))}")
}
}
User(id=6ad3d69fcad26ed85a622b62, name=Alice, email=alice@example.com, age=34, roles=[admin, dev], address=Address(city=Berlin, country=DE), active=true)
-- age >= 25, oldest first
Carol 41
Alice 34
Bob 27
-- devs in Berlin
Alice
-- inactive (field stored as is_active)
Carol
-- projection into another class, page 2 of size 2
NameAndAge(name=Carol, age=41)
NameAndAge(name=Dave, age=19)
-- distinct cities
[Berlin, Warsaw]
count with roles: 3
A few query features are worth remembering:
- Arrays match by element.
Filters.eq("roles", "dev")matches any user whoserolesarray contains"dev". - Dot notation reaches into embedded documents.
"address.city"queries a field of a nested object."roles.0"refers to the first array element, soFilters.exists("roles.0")means "the array isn't empty". - Projections reduce what's sent over the network.
withDocumentClass<NameAndAge>()gives you a view of the same collection that decodes into a smaller class. skip+limitgives you pagination. For deep pages, filter on the last seen sort key (age > lastAge) instead.skip(100000)still has to walk past 100,000 documents.
Type-safe queries and updates
String field names break silently when you rename a property. The com.mongodb.kotlin.client.model package from mongodb-driver-kotlin-extensions mirrors Filters, Updates, Sorts, Projections and Aggregates, but takes KProperty references. The / operator builds a path into a nested class. @BsonId and @BsonProperty are respected, so Product::sku below becomes _id.
The same example also shows the main write operations:
import com.mongodb.client.model.FindOneAndUpdateOptions
import com.mongodb.client.model.ReturnDocument
import com.mongodb.client.model.UpdateOptions
import com.mongodb.kotlin.client.MongoClient
import com.mongodb.kotlin.client.model.Filters
import com.mongodb.kotlin.client.model.Sorts
import com.mongodb.kotlin.client.model.Updates
import com.mongodb.kotlin.client.model.div
import org.bson.codecs.pojo.annotations.BsonId
data class Stock(val warehouse: Int, val store: Int)
data class Product(
@BsonId val sku: String,
val name: String,
val price: Double,
val tags: List<String> = emptyList(),
val stock: Stock = Stock(0, 0),
)
fun main() {
MongoClient.create("mongodb://localhost:27017").use { client ->
val products = client.getDatabase("shop").getCollection<Product>("catalog")
products.drop()
products.insertMany(
listOf(
Product("KB-1", "Keyboard", 49.99, listOf("usb"), Stock(12, 3)),
Product("MS-1", "Mouse", 19.50, listOf("usb", "wireless"), Stock(40, 0)),
Product("MN-1", "Monitor", 189.00, listOf("hdmi"), Stock(2, 1)),
)
)
// type-safe filters: property references instead of strings
val cheap = products.find(Filters.lt(Product::price, 50.0))
.sort(Sorts.ascending(Product::price))
.map { it.name }
.toList()
println("cheap: $cheap")
// nested field: Product::stock / Stock::warehouse is "stock.warehouse"
val lowStock = products.find(Filters.lte(Product::stock / Stock::warehouse, 5)).toList()
println("low stock: ${lowStock.map { it.sku }}")
// updateOne with several operators at once
val r1 = products.updateOne(
Filters.eq(Product::sku, "KB-1"),
Updates.combine(
Updates.set(Product::price, 44.99),
Updates.inc(Product::stock / Stock::warehouse, -1),
Updates.addToSet(Product::tags, "sale"),
)
)
println("matched=${r1.matchedCount} modified=${r1.modifiedCount}")
// updateMany: 10% off everything tagged usb
val r2 = products.updateMany(Filters.all(Product::tags, "usb"), Updates.mul(Product::price, 0.9))
println("discounted ${r2.modifiedCount} products")
// upsert: insert when nothing matches
val r3 = products.updateOne(
Filters.eq(Product::sku, "HS-1"),
Updates.combine(Updates.set(Product::name, "Headset"), Updates.set(Product::price, 59.0)),
UpdateOptions().upsert(true)
)
println("upserted id: ${r3.upsertedId?.asString()?.value}")
// atomically decrement stock and get the new document back
val updated = products.findOneAndUpdate(
Filters.and(Filters.eq(Product::sku, "MN-1"), Filters.gt(Product::stock / Stock::store, 0)),
Updates.inc(Product::stock / Stock::store, -1),
FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)
)
println("after sale: $updated")
// replace the whole document
products.replaceOne(Filters.eq(Product::sku, "MS-1"), Product("MS-1", "Mouse v2", 24.0, listOf("usb-c")))
println("replaced: ${products.find(Filters.eq(Product::sku, "MS-1")).first()}")
val d = products.deleteMany(Filters.lt(Product::price, 30.0))
println("deleted ${d.deletedCount}")
products.find().forEach { println("%-6s %-9s %7.2f".format(it.sku, it.name, it.price)) }
}
}
cheap: [Mouse, Keyboard]
low stock: [MN-1]
matched=1 modified=1
discounted 2 products
upserted id: HS-1
after sale: Product(sku=MN-1, name=Monitor, price=189.0, tags=[hdmi], stock=Stock(warehouse=2, store=0))
replaced: Product(sku=MS-1, name=Mouse v2, price=24.0, tags=[usb-c], stock=Stock(warehouse=0, store=0))
deleted 1
KB-1 Keyboard 40.49
MN-1 Monitor 189.00
HS-1 Headset 59.00
- Update operators change fields in place on the server:
$set,$inc,$mul,$push,$addToSet,$pull,$unsetand more. Each update is atomic for a single document. Two clients runningincon the same counter never lose an update, which a read-modify-write in Kotlin can't promise. updateOne/updateManyreturnmatchedCountandmodifiedCount. A document that matched but already had the new values counts as matched, not modified.upsert(true)inserts a new document when nothing matches. The new document gets the fields from the equality filter plus the$setfields. Defaults in the data class cover the fields that weren't set.findOneAndUpdatefinds, modifies and returns a document in one atomic step. The filterstock.store > 0together with$inc: -1is a safe way to sell the last item without overselling. UseReturnDocument.AFTERto get the updated version (the default is the version before the update).replaceOneswaps out the whole document but keeps its_id.
Indexes and write errors
Without an index, every query scans the whole collection. Create indexes for the fields you filter and sort on. createIndex is idempotent, so calling it at application startup is a common pattern. A unique index also enforces a constraint, the way a UNIQUE column does in SQL.
import com.mongodb.ErrorCategory
import com.mongodb.MongoBulkWriteException
import com.mongodb.MongoWriteException
import com.mongodb.client.model.BulkWriteOptions
import com.mongodb.client.model.IndexOptions
import com.mongodb.client.model.InsertOneModel
import com.mongodb.client.model.Indexes
import com.mongodb.kotlin.client.MongoClient
import com.mongodb.kotlin.client.model.Filters
import org.bson.Document
import org.bson.codecs.pojo.annotations.BsonId
import org.bson.types.ObjectId
import java.time.Instant
import java.util.concurrent.TimeUnit
data class Account(
@BsonId val id: ObjectId = ObjectId(),
val email: String,
val country: String,
val createdAt: Instant = Instant.now(),
)
fun main() {
MongoClient.create("mongodb://localhost:27017").use { client ->
val db = client.getDatabase("app")
val accounts = db.getCollection<Account>("accounts")
accounts.drop()
// unique index: the database rejects a second account with the same email
accounts.createIndex(Indexes.ascending("email"), IndexOptions().unique(true))
// compound index for "accounts in a country, newest first"
accounts.createIndex(Indexes.compoundIndex(Indexes.ascending("country"), Indexes.descending("createdAt")))
accounts.listIndexes().forEach { println("${it["name"]} -> ${it["key"]} unique=${it["unique"] ?: false}") }
accounts.insertOne(Account(email = "alice@example.com", country = "DE"))
try {
accounts.insertOne(Account(email = "alice@example.com", country = "PL"))
} catch (e: MongoWriteException) {
if (e.error.category == ErrorCategory.DUPLICATE_KEY) {
println("duplicate: code=${e.code}")
} else throw e
}
// unordered bulk insert: keeps going after an error and reports all failures
val batch = listOf("bob@example.com", "alice@example.com", "carol@example.com")
.map { InsertOneModel(Account(email = it, country = "PL")) }
try {
accounts.bulkWrite(batch, BulkWriteOptions().ordered(false))
} catch (e: MongoBulkWriteException) {
println("inserted ${e.writeResult.insertedCount}, failed at indexes ${e.writeErrors.map { it.index }}")
}
println("total accounts: ${accounts.countDocuments()}")
// the query planner uses the compound index
val plan = accounts.find(Filters.eq(Account::country, "PL"))
.sort(Document("createdAt", -1))
.explain()
val winning = plan.getEmbedded(listOf("queryPlanner", "winningPlan"), Document::class.java)
println("plan: ${winning.toJson().let { Regex("\"stage\": \"(\\w+)\"").findAll(it).map { m -> m.groupValues[1] }.toList() }}")
// TTL index: MongoDB deletes sessions about 1 hour after createdAt
val sessions = db.getCollection<Document>("sessions")
sessions.drop()
sessions.createIndex(Indexes.ascending("createdAt"), IndexOptions().expireAfter(1, TimeUnit.HOURS))
println("ttl index: ${sessions.listIndexes().toList().last().toJson()}")
}
}
_id_ -> Document{{_id=1}} unique=false
email_1 -> Document{{email=1}} unique=true
country_1_createdAt_-1 -> Document{{country=1, createdAt=-1}} unique=false
duplicate: code=11000
inserted 2, failed at indexes [1]
total accounts: 3
plan: [FETCH, IXSCAN]
ttl index: {"v": 2, "key": {"createdAt": 1}, "name": "createdAt_1", "expireAfterSeconds": 3600}
- A failed single write throws
MongoWriteException. Checke.error.category == ErrorCategory.DUPLICATE_KEY(error code 11000) to map it to a "this email is already registered" message. bulkWritesends many operations in one round trip. Withordered(false)the server keeps going after an error, andMongoBulkWriteExceptiontells you which operations failed.explain()shows the query plan.IXSCANmeans an index was used.COLLSCANon a large collection means you're missing an index.- A TTL index on a date field makes the server delete expired documents in the background (about once a minute). It's a good fit for sessions, password reset tokens and logs.
Instantandjava.util.Dateare stored as BSON dates.
Aggregation
The aggregation pipeline is MongoDB's answer to GROUP BY, joins and reports. A pipeline is a list of stages, and each stage transforms the stream of documents: $match filters, $unwind turns one document with an array into one document per element, $group aggregates, $project reshapes, $sort and $limit do what they say. $lookup joins documents from another collection.
import com.mongodb.client.model.Accumulators
import com.mongodb.client.model.Aggregates
import com.mongodb.client.model.Filters
import com.mongodb.client.model.Sorts
import com.mongodb.kotlin.client.MongoClient
import org.bson.Document
import org.bson.codecs.pojo.annotations.BsonId
data class Item(val product: String, val qty: Int, val price: Double)
data class Order(val customer: String, val status: String, val items: List<Item>)
// shape of one aggregation result row
data class CustomerTotal(@BsonId val customer: String, val orders: Int, val revenue: Double)
fun main() {
MongoClient.create("mongodb://localhost:27017").use { client ->
val orders = client.getDatabase("shop").getCollection<Order>("orders")
orders.drop()
orders.insertMany(
listOf(
Order("alice", "paid", listOf(Item("Keyboard", 1, 49.99), Item("Mouse", 2, 19.50))),
Order("bob", "paid", listOf(Item("Monitor", 1, 189.00))),
Order("alice", "paid", listOf(Item("Mouse", 1, 19.50))),
Order("carol", "cancelled", listOf(Item("Monitor", 2, 189.00))),
Order("bob", "paid", listOf(Item("Keyboard", 2, 49.99))),
)
)
// revenue per customer from paid orders
val totals = orders.aggregate<CustomerTotal>(
listOf(
Aggregates.match(Filters.eq("status", "paid")),
Aggregates.unwind("\$items"),
Aggregates.group(
"\$customer",
Accumulators.addToSet("orderIds", "\$_id"),
Accumulators.sum("revenue", Document("\$multiply", listOf("\$items.qty", "\$items.price"))),
),
Aggregates.project(
Document("orders", Document("\$size", "\$orderIds"))
.append("revenue", Document("\$round", listOf("\$revenue", 2)))
),
Aggregates.sort(Sorts.descending("revenue")),
)
)
totals.forEach { println(it) }
// best-selling products, as plain Documents
orders.aggregate<Document>(
listOf(
Aggregates.match(Filters.ne("status", "cancelled")),
Aggregates.unwind("\$items"),
Aggregates.group("\$items.product", Accumulators.sum("sold", "\$items.qty")),
Aggregates.sort(Sorts.orderBy(Sorts.descending("sold"), Sorts.ascending("_id"))),
Aggregates.limit(2),
)
).forEach { println("${it.getString("_id")}: ${it.getInteger("sold")}") }
}
}
CustomerTotal(customer=bob, orders=2, revenue=288.98)
CustomerTotal(customer=alice, orders=2, revenue=108.49)
Keyboard: 3
Mouse: 3
"\$customer"is a field reference. Kotlin needs the\$escape, otherwise$customerwould be a string template.aggregate<CustomerTotal>()decodes each result row into a data class. The_idproduced by$groupmaps to the@BsonIdproperty.- Put
$matchfirst so the pipeline can use an index and later stages see fewer documents. - The
Orderdata class has no id property. The server still adds an_idon insert, and the driver ignores it when decoding.
Transactions
A single-document update is always atomic. Most of the time that's enough if you design documents so that data which changes together lives together. When you must change several documents atomically, like moving money between two wallets, use a multi-document transaction. Transactions need a replica set or a sharded cluster (a single-node replica set is fine for development).
import com.mongodb.kotlin.client.ClientSession
import com.mongodb.kotlin.client.MongoClient
import com.mongodb.kotlin.client.MongoCollection
import com.mongodb.kotlin.client.model.Filters
import com.mongodb.kotlin.client.model.Updates
import org.bson.codecs.pojo.annotations.BsonId
import java.time.Instant
data class Wallet(@BsonId val owner: String, val balance: Long)
data class Transfer(val from: String, val to: String, val amount: Long, val at: Instant = Instant.now())
class InsufficientFunds(owner: String) : RuntimeException("insufficient funds in $owner's wallet")
fun transfer(
session: ClientSession,
wallets: MongoCollection<Wallet>,
log: MongoCollection<Transfer>,
from: String, to: String, amount: Long,
) {
session.withTransaction({
// only debit when the balance is high enough; the filter makes this atomic
val debited = wallets.updateOne(
session,
Filters.and(Filters.eq(Wallet::owner, from), Filters.gte(Wallet::balance, amount)),
Updates.inc(Wallet::balance, -amount),
)
if (debited.modifiedCount == 0L) throw InsufficientFunds(from)
wallets.updateOne(session, Filters.eq(Wallet::owner, to), Updates.inc(Wallet::balance, amount))
log.insertOne(session, Transfer(from, to, amount))
})
}
fun main() {
MongoClient.create("mongodb://localhost:27017").use { client ->
val db = client.getDatabase("bank")
val wallets = db.getCollection<Wallet>("wallets")
val log = db.getCollection<Transfer>("transfers")
wallets.drop()
log.drop()
wallets.insertMany(listOf(Wallet("alice", 100), Wallet("bob", 20)))
client.startSession().use { session ->
transfer(session, wallets, log, "alice", "bob", 70)
try {
transfer(session, wallets, log, "alice", "bob", 50)
} catch (e: InsufficientFunds) {
println("rolled back: ${e.message}")
}
}
wallets.find().forEach { println("${it.owner}: ${it.balance}") }
log.find().forEach { println("${it.from} -> ${it.to}: ${it.amount}") }
}
}
rolled back: insufficient funds in alice's wallet
alice: 30
bob: 90
alice -> bob: 70
- Every operation in the transaction must receive the
sessionas its first argument. An operation without it runs outside the transaction. withTransactioncommits when the block returns normally. It aborts when the block throws and rethrows the exception. It also retries the whole block on transient errors such as write conflicts, so keep the block free of side effects other than database writes.- The second transfer debited nothing, threw
InsufficientFunds, and left no trace in either collection.
Coroutines
With mongodb-driver-kotlin-coroutine the API is almost the same, but single-result operations are suspend functions and find() / aggregate() return a Flow. Nothing blocks a thread, so it fits naturally into Ktor (see HTTP with Ktor) and other coroutine code.
import com.mongodb.kotlin.client.coroutine.MongoClient
import com.mongodb.kotlin.client.coroutine.MongoCollection
import com.mongodb.kotlin.client.model.Filters
import com.mongodb.kotlin.client.model.Sorts
import com.mongodb.kotlin.client.model.Updates
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.runBlocking
import org.bson.codecs.pojo.annotations.BsonId
data class Article(@BsonId val slug: String, val title: String, val views: Long = 0, val tags: List<String> = emptyList())
class ArticleRepository(private val articles: MongoCollection<Article>) {
suspend fun save(article: Article) {
articles.insertOne(article)
}
suspend fun findBySlug(slug: String): Article? =
articles.find(Filters.eq(Article::slug, slug)).firstOrNull()
suspend fun recordView(slug: String) {
articles.updateOne(Filters.eq(Article::slug, slug), Updates.inc(Article::views, 1))
}
// find() returns a Flow: documents are fetched in batches as you collect
fun popular() = articles.find().sort(Sorts.descending(Article::views))
}
fun main() = runBlocking {
MongoClient.create("mongodb://localhost:27017").use { client ->
val collection = client.getDatabase("blog").getCollection<Article>("articles")
collection.drop()
val repo = ArticleRepository(collection)
repo.save(Article("hello-kotlin", "Hello Kotlin", tags = listOf("kotlin")))
repo.save(Article("mongo-tips", "MongoDB tips", tags = listOf("mongodb", "kotlin")))
repo.save(Article("gradle-101", "Gradle 101", tags = listOf("build")))
// 100 concurrent increments; $inc is atomic so none are lost
coroutineScope {
(1..100).map { i ->
async { repo.recordView(if (i % 4 == 0) "hello-kotlin" else "mongo-tips") }
}.awaitAll()
}
println(repo.findBySlug("mongo-tips"))
println(repo.findBySlug("missing"))
val kotlinTitles = repo.popular()
.filter { "kotlin" in it.tags }
.map { "${it.title} (${it.views})" }
.toList()
println(kotlinTitles)
}
}
Article(slug=mongo-tips, title=MongoDB tips, views=75, tags=[mongodb, kotlin])
null
[MongoDB tips (75), Hello Kotlin (25)]
The flow is cold. The query runs when you collect it, and operators like filter, map and take work as usual. Filtering in Kotlin is shown here only to demonstrate Flow operators. In real code put conditions like "kotlin" in tags in the query (Filters.all(Article::tags, "kotlin")) so the server does the work.
Configuration for production
The connection string handles most options (mongodb+srv://user:pass@cluster.example.net/?retryWrites=true&w=majority is typical for MongoDB Atlas). For more control use MongoClientSettings:
import com.mongodb.ConnectionString
import com.mongodb.MongoClientSettings
import com.mongodb.MongoTimeoutException
import com.mongodb.WriteConcern
import com.mongodb.kotlin.client.MongoClient
import org.bson.Document
import java.util.concurrent.TimeUnit
fun main() {
val uri = System.getenv("MONGODB_URI") ?: "mongodb://localhost:27017"
val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.applicationName("orders-service")
.applyToConnectionPoolSettings {
it.maxSize(50) // max connections per server
.minSize(5)
.maxWaitTime(2, TimeUnit.SECONDS) // wait for a free connection
}
.applyToClusterSettings { it.serverSelectionTimeout(3, TimeUnit.SECONDS) }
.applyToSocketSettings { it.connectTimeout(2, TimeUnit.SECONDS) }
.writeConcern(WriteConcern.MAJORITY)
.build()
MongoClient.create(settings).use { client ->
val info = client.getDatabase("admin").runCommand(Document("buildInfo", 1))
println("server version: ${info.getString("version")}")
}
// a server that isn't there: fails after serverSelectionTimeout
val bad = MongoClientSettings.builder()
.applyConnectionString(ConnectionString("mongodb://127.0.0.1:1"))
.applyToClusterSettings { it.serverSelectionTimeout(1, TimeUnit.SECONDS) }
.build()
MongoClient.create(bad).use { client ->
try {
client.getDatabase("app").runCommand(Document("ping", 1))
} catch (e: MongoTimeoutException) {
println("timeout: ${e.message?.substringBefore(". Client view")}")
}
}
}
server version: 9.0.4
timeout: Timed out while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}
- Read the URI (it contains the password) from the environment, not source code. See Environment variables.
serverSelectionTimeout(default 30 seconds) is how long an operation waits when no suitable server is reachable. Lower it if you'd rather fail fast.maxSizeof the connection pool defaults to 100 per server. The pool is shared by all threads or coroutines using the client.WriteConcern.MAJORITY(the default in modern servers) acknowledges a write only after most replica set members have it, so it survives a failover.
Best practices
- Create one
MongoClientper application and share it. Close it on shutdown. - Model for your queries. Embed data that is read together (an order and its items). Reference data that grows without bound or is shared (a user's millions of events).
- Index every filter and sort you run often, and check the query plan with
explain(). - Use update operators (
$inc,$set,$push) andfindOneAndUpdateinstead of read-modify-write in Kotlin. - Never build queries from strings with user input. Pass values through
Filtersso they can't change the query's structure. - Keep documents well under the 16 MB limit. Arrays that grow forever are a design smell.
- For a relational alternative, see PostgreSQL. For caching in front of MongoDB, see Redis.