I’m converting from a local Realm to one backed by MongoDB server. I follow the tutorial and all seems to go well but when I attempt to write the code to connect, I get an Unresolved Reference on MongoClient.create.
My code looks like this:
import io.realm.kotlin.Realm
import io.realm.kotlin.RealmConfiguration
import io.realm.kotlin.ext.isManaged
import io.realm.kotlin.ext.query
import io.realm.kotlin.query.RealmResults
import org.mongodb.kbson.ObjectId
import todaysDateAsLong
import org.bson.Document
import com.mongodb.reactivestreams.client.MongoClient
import kotlinx.coroutines.runBlocking
fun connectToRealmServer() : Realm {
// Replace the placeholders with your credentials and hostname
val uri = "mongodb+srv://OptimalHealth:<password>@atlascluster.j1c9yxd.mongodb.net/?retryWrites=true&w=majority&appName=AtlasCluster"
val mongoClient = MongoClient.create(uri) //UNRESOLVED HERE
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
runBlocking {
val doc = collection.find(eq("title", "Back to the Future")).firstOrNull() //AND HERE on the EQ
if (doc != null) {
println(doc.toJson())
} else {
println("No matching documents found.")
}
}
mongoClient.close()
}
My build.gradle looks like this (cut down to just the germane area)
dependencies {
implementation(libs.androidx.material)
implementation(libs.androidx.material3.android)
implementation(libs.mongodb.driver.kotlin.coroutine)
implementation(libs.bson.kotlinx)
}
And the libs.versions.toml looks like this:
mongodbDriverKotlinCoroutine = "5.0.0"
....
mongodb-driver-kotlin-coroutine = { module = "org.mongodb:mongodb-driver-kotlin-coroutine", version.ref = "mongodbDriverKotlinCoroutine" }
It acts like it’s a classpath issue assuming the tutorial is correct, but everything looks correct to me. Here is the structure in Android Studio.
What is it that I’m doing wrong, please?