Skip to content

Instantly share code, notes, and snippets.

@rozza
Created March 17, 2023 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rozza/f746094f52700c3b12c4ba7d25358959 to your computer and use it in GitHub Desktop.
Save rozza/f746094f52700c3b12c4ba7d25358959 to your computer and use it in GitHub Desktop.
import com.mongodb.{ServerApi, ServerApiVersion}
import org.mongodb.scala.{ConnectionString, MongoClient, MongoClientSettings}
import org.mongodb.scala.bson.Document
import scala.concurrent.Await
import scala.concurrent.duration.DurationInt
import scala.util.Using
object MongoClientConnectionExample {
def main(args: Array[String]): Unit = {
// Replace the placeholders with your credentials and hostname
val connectionString = "mongodb+srv://<username>:<password>@<svrHostName>";
val serverApi = ServerApi.builder.version(ServerApiVersion.V1).build()
val settings = MongoClientSettings
.builder()
.applyConnectionString(ConnectionString(connectionString))
.serverApi(serverApi)
.build()
Using(MongoClient(settings)) { mongoClient =>
val database = mongoClient.getDatabase("admin")
val ping = database.runCommand(Document("ping" -> 1)).head()
Await.result(ping, 10.seconds) // Wait for future to return
System.out.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