Skip to content

Quick start

Choose between suspension and blocking

Add the dependency

KtMongo is currently not published to MavenCentral. To import it into your projects, use a Gradle composite build.

Connect to a database

First, instantiate a client and request a specific database:

val database = MongoClient.create("mongodb://localhost:PORT-NUMBER")
    .getDatabase("foo")

To configure more options, see the official documentation.

Access a collection

First, create a class that represents the documents stored in the collection:

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

Now, instantiate the collection:

val collection = database.getCollection<User>("users")
    .asKtMongo()

Perform a simple operation

Now that we have access to the collection, we can perform operations on it:

val count = collection.countDocumentsEstimated()