mongodbasynchronouskotlinnonblockingkotlin-coroutines

Is there a good library for Kotlin Coroutines to access Mongo asynchronously?


I'm starting a new project in the JVM with lots of IO. At some point, I have to save some stuff in a Mongo database. My idea is to use a nonblocking approach with Kotlin coroutines.

I know there is an official reative streams driver for Mongo and the support looks good. But in this case I would need to "create bridges" between the streams and the coroutines. My question is regarding this point: does anyone know a better or simpler way of doing it?


Solution

  • Take a look at the KMongo project. It has coroutines support:

    import org.litote.kmongo.reactivestreams.*  // KMongo reactivestreams extensions
    import org.litote.kmongo.coroutine.* // KMongo coroutine extensions
    
    data class Jedi(val name: String, val age: Int)
    
    val client = KMongo.createClient().coroutine //use coroutine extension
    val database = client.getDatabase("test") //normal java driver usage
    val col = database.getCollection<Jedi>() //KMongo extension method
    
    //async now
    runBlocking {
        col.insertOne(Jedi("Luke Skywalker", 19))
    
        val yoda : Jedi? = col.findOne(Jedi::name eq "Yoda")
    
        (...)
    }