Skip to content

MongoClient

Entry-point to the KtMongo Multiplatform driver.

Organizing data

Accessing MongoDB data happens in three steps:

  • MongoClient: represents the connection to the MongoDB application, handles the lifecycle and the configuration.

  • MongoDatabase (accessed with MongoClient.database): each database groups data together. This allows deploying multiple applications (or the same application multiple times) without name collisions.

  • MongoCollection (accessed with MongoDatabase.collection): each collection stores data together. Documents in a collection may have a different structure.

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

MongoClient

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

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 override fun close()

database

Creates a MongoDatabase 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 MongoClient.