MongoClient¶
interface MongoClient : AutoCloseable
Entry-point to the KtMongo drivers.
This interface exists to unify the API of the different KtMongo drivers. Each implementation may add its own specificities.
Each implementation provides its own way to obtain an instance of this interface.
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 withMongoClient.database): each database groups data together. This allows deploying multiple applications (or the same application multiple times) without name collisions. -
MongoCollection(accessed withMongoDatabase.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 = // Implementation-dependent accessor
val database = client.database("my-app")
val users = database.collection<User>("users")
println("The database contains ${users.count()} users.")
}
Functions¶
close¶
expect abstract fun close()
database¶
abstract fun database(name: String): MongoDatabase
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.
To learn more about the restrictions on the database name, see MongoDatabase.name.
For an example, see MongoClient.