Created
March 30, 2023 14:00
-
-
Save rozza/b54e566c1a29f464ad1c6e58bba3102a to your computer and use it in GitHub Desktop.
Kotlin coroutine driver with server api example of connecting to the database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.bson.Document | |
import com.mongodb.ConnectionString | |
import com.mongodb.MongoClientSettings | |
import com.mongodb.ServerApi | |
import com.mongodb.ServerApiVersion | |
import com.mongodb.kotlin.client.coroutine.MongoClient | |
import kotlinx.coroutines.runBlocking | |
object MongoClientConnectionExample { | |
fun main() { | |
// Replace the placeholders with your credentials and hostname | |
val connectionString = "mongodb+srv://<username>:<password>@<svrHostName>"; | |
val serverApi = ServerApi.builder() | |
.version(ServerApiVersion.V1) | |
.build() | |
val mongoClientSettings = MongoClientSettings.builder() | |
.applyConnectionString(ConnectionString(connectionString)) | |
.serverApi(serverApi) | |
.build(); | |
// Create a new client and connect to the server | |
MongoClient.create(mongoClientSettings).use { mongoClient -> | |
val database = mongoClient.getDatabase("admin") | |
runBlocking { | |
database.runCommand(Document("ping", 1)) | |
} | |
println("Pinged your deployment. You successfully connected to MongoDB!") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment