创建 MongoClient
Overview
要连接到 MongoDB 部署,您需要满足两个条件:
连接 URI,也称为连接字符串,它告诉Scala驾驶员要连接到哪个MongoDB 部署。
一个 MongoClient对象,用于创建与 MongoDB 部署的连接并允许您对MongoDB 部署执行操作。
您还可以使用 MongoClientSettings
自定义Scala驾驶员在连接到MongoDB时的行为方式。
本指南向您介绍如何创建连接string并使用 MongoClient
对象连接到MongoDB 。
连接 URI
标准连接string包括以下组件:
组件 | 说明 |
---|---|
| 必需。将其标识为标准连接格式中字符串的前缀。 |
| |
| 必需。 运行 MongoDB 的主机和可选端口号。 如果不包含端口号,驱动程序将使用默认端口 |
| 可选。 如果连接string包含 |
| 可选。 一个查询string ,它将特定于连接的选项指定为 |
Atlas 连接示例
要连接到Atlas上的MongoDB 部署,必须首先创建一个客户端。
您可以将连接 URI 以string形式传递给 MongoClient.create()
方法,以连接到MongoDB实例:
// Replace the placeholder with your Atlas connection string val connectionString = "<connection string>" // Create a new client and connect to the server val mongoClient = MongoClient(connectionString) val database = mongoClient.getDatabase("sample_mflix")
您还可以通过将 MongoClientSettings
对象传递给 MongoClient
对象来创建具有所需配置的客户端。
要实例化 MongoClientSettings
对象,请调用 builder()
方法,然后链接 applyConnectionString()
方法并传入连接字符串。您还可以使用 builder()
方法指定任何其他客户端选项。获得所需配置后,调用 build()
方法。
您可以设置 stable API 版本客户端选项,以避免升级到新服务器版本时发生破坏性变更 (breaking change)。要了解有关 Stable API 功能的更多信息,请参阅Stable API 页面。
以下代码展示了在连接到 Atlas 上的 MongoDB 部署时,如何指定连接字符串和 Stable API 客户端选项,并检查连接是否成功:
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 placeholder with your Atlas connection string val connectionString = "<connection string>" // Construct a ServerApi instance using the ServerApi.builder() method val serverApi = ServerApi.builder.version(ServerApiVersion.V1).build() val settings = MongoClientSettings .builder() .applyConnectionString(ConnectionString(connectionString)) .serverApi(serverApi) .build() // Create a new client and connect to the server Using(MongoClient(settings)) { mongoClient => // Send a ping to confirm a successful connection val database = mongoClient.getDatabase("admin") val ping = database.runCommand(Document("ping" -> 1)).head() Await.result(ping, 10.seconds) System.out.println("Pinged your deployment. You successfully connected to MongoDB!") } } }
API 文档
有关使用Scala驾驶员创建 MongoClient
对象的更多信息,请参阅以下API文档: