Skip to content

MultiplatformMongoClient

Entry-point to the KtMongo Multiplatform driver.

The Multiplatform driver provides a coroutine-aware API which works on all supported Kotlin platforms.

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 = MongoClient(
        hostname = "localhost",
        port = 27017,
        coroutineContext = currentCoroutineContext(),
    )

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

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

Constructors

MultiplatformMongoClient

@ExperimentalAtomicApi
suspend fun MultiplatformMongoClient(
    hostname: String = "localhost", 
    port: Int = 27017, 
    coroutineContext: CoroutineContext, 
    bsonFactory: BsonFactory = BsonFactory(), 
    objectIdGenerator: ObjectIdGenerator = ObjectIdGenerator.Default(), 
    propertyNameStrategy: PropertyNameStrategy = PropertyNameStrategy.Default
): MultiplatformMongoClient

Connects to the database at the specified hostname and port.

By default, connects to "mongo://localhost:27017".

Example

val job = Job()
val client = MongoClient(coroutineContext = job)
val collection = client.database("mydb").collection<User>("mycollection")

println(collection.count())

job.cancel("Shutting down the client")

Parameters

  • coroutineContext: The coroutine context used to maintain the connection, including background tasks. Specify a custom Job to control the lifecycle of the client (call Job.cancel to close the client).

  • bsonFactory: The BsonFactory instance used to serialize and deserialize BSON values. Pass a custom instance to configure polymorphic serialization and other matters.

  • objectIdGenerator: The algorithm used to generate new ObjectId instances.

  • propertyNameStrategy: The algorithm used to convert from the DSL path syntax accesses to MongoDB field paths.

Properties

context

factory

Functions

close

open suspend override fun close()

database

open override fun database(name: String): MultiplatformMongoDatabase

Creates a MultiplatformMongoDatabase object.

This method is purely a client-side operation, it does nothing in the MongoDB server. In MongoDB, databases and collections are created implicitly on the first insert.

For an example, see MultiplatformMongoClient.

toString

open override fun toString(): String