capped

open fun capped(sizeBytes: Long, max: Long? = null)(source)

Specifies that this collection is capped: it has a maximum size. Once that size is reached, MongoDB removes the oldest documents.

Performance

Capped collection writes are often slower than TTL indexes and regular collections.

It is recommended to avoid updates in capped collections.

Example

class User(
val _id: ObjectId,
val name: String,
val age: Int,
)

class UserEditLog(
val date: Instant,
val user: ObjectId,
val previousName: String,
val newName: String,
)

val editLog = database.collection<UserEditLog>("user-edit-log")

editLog.create {
capped(sizeBytes = 1024 * 1024) // 1 MiB
}

editLog.insertOne(
UserEditLog(
date = clock.now(),
user = user._id,
previousName = previousName,
newName = user.name,
)
)

External resources