All Downloads are FREE. Search and download functionalities are using the official Maven repository.

invirt.data.mongodb.MongoDb.kt Maven / Gradle / Ivy

There is a newer version: 0.10.11
Show newest version
package invirt.data.mongodb

import com.mongodb.ConnectionString
import com.mongodb.kotlin.client.MongoClient
import com.mongodb.kotlin.client.MongoCollection
import com.mongodb.kotlin.client.MongoDatabase
import org.bson.BsonInt64
import org.bson.Document
import org.slf4j.LoggerFactory

class MongoDb(connectionString: String) {

    val database: MongoDatabase

    init {
        log.info("MongoDB connection string: ${connectionString.replace("://.*@".toRegex(), "://*****@")}")
        val client = MongoClient.create(connectionString)
        val connection = ConnectionString(connectionString)
        val databaseName = connection.database!!

        database = client.getDatabase(databaseName)
        database.runCommand(Document("ping", BsonInt64(1)))
        log.info("Successfully pinged MongoDB database '${databaseName}' at '${connection.hosts.joinToString(", ")}'    ")
    }

    inline fun  getCollection(): MongoCollection {
        val collection = database.getCollection(collectionName())
        collection.createIndexes()
        return collection
    }

    companion object {
        private val log = LoggerFactory.getLogger(MongoDb::class.java)
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy