Skip to content

CoroutineMongoClient

Entry-point to the KtMongo Coroutines driver.

The Coroutine client provides a coroutine-aware API which internally uses the official Kotlin driver.

Organizing data

Accessing MongoDB data happens in three steps:

Example

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

fun main() = runBlocking {
    val client = CoroutineMongoClient("mongodb://localhost:27017")

    val database = client.database("my-app")
    val users = database.collection<User>("users")

    println("The database contains ${users.count()} users.")
}

See also

  • asKtMongo: Convert an existing instance from the official Kotlin driver.

Constructors

CoroutineMongoClient

fun CoroutineMongoClient(connectionString: String = "mongodb://localhost:27017"): CoroutineMongoClient

Instantiates a KtMongo CoroutineMongoClient using an existing client from the official Kotlin driver.

This method allows taking advantage of the full configuration power of the official client.

Example

fun main() = runBlocking {
    val client = CoroutineMongoClient()

    val database = client.database("my-app")
    val users = database.collection<UserDto>("users")

    println("Users: ${users.count()}")
}

Functions

asOfficial

abstract fun asOfficial(): MongoClient

Obtains the underlying MongoDB client from the official Kotlin driver.

close

abstract fun close()

database

abstract override fun database(name: String): CoroutineMongoDatabase