文档菜单
文档首页
/ / /
Scala
/

连接到 MongoDB

在本页

  • 先决条件
  • MongoClient
  • 连接 URI
  • 连接到 MongoDB Atlas
  • 连接到本地 MongoDB 部署
  • 连接到副本集
  • 连接到分片集群
  • 连接选项
  • 连接教程

本指南描述了如何使用 Scala 驱动程序连接到 MongoDB。

使用MongoClient() 方法连接到正在运行的 MongoDB 部署。

重要

以下示例并未提供实例化 MongoClient 的所有方式的完整列表。对于 MongoClient 伴生方法的完整列表,请参阅MongoClient API 文档.

注意

我们 强烈建议 系统保持活动设置应配置为较短的超时时间。

有关更多信息,请参阅服务器手册 FAQ 中的是否 TCP 保持活动时间会影响 MongoDB 部署?问题及其答案。

您必须设置以下组件以运行本指南中的代码示例

  • 运行中的 MongoDB 部署以连接到。例如,要连接到独立部署,您必须可以访问运行的独立部署。

  • 在您的项目中安装了驱动依赖项。有关如何安装驱动程序的说明,请参阅安装.

  • 以下导入语句

    import org.mongodb.scala._
    import scala.collection.JavaConverters._

MongoClient 实例表示数据库的连接池。即使运行多个并发操作,也只需要一个 MongoClient 实例。

重要

通常,您只为特定 MongoDB 部署(如独立部署、副本集或分片集群)创建一个 MongoClient 实例,并在整个应用程序中使用该客户端。但是,如果您创建了多个实例,请注意以下事项

  • 所有资源使用限制(例如,最大连接数)均适用于每个 MongoClient 实例。

  • 要销毁实例,请调用 MongoClient.close() 方法以清理资源。

连接URI提供了一组指令,驱动程序使用这些指令连接到MongoDB部署。它指导驱动程序如何连接到MongoDB,以及连接期间应该如何行为。以下图解释了示例连接URI的各个部分。

An example of a connection string that demonstrates the protocol, credentials, hostname or IP, port, and connection options

在此示例中,您连接到一个具有DNS SRV记录的Atlas MongoDB部署。有关更多详细信息,请参阅DNS Seed List连接格式文档。此格式在部署方面提供了灵活性,并能够在不重新配置客户端的情况下更改轮询中的服务器。

注意

如果您的部署在MongoDB Atlas上,请参阅Atlas驱动程序连接指南并选择Scala从语言下拉菜单中检索您的连接字符串。

如果您连接到的实例或副本集没有DNS SRV地址,您必须使用mongodb作为协议,该协议指定了标准连接字符串格式

在协议之后,连接字符串包含您的凭据(如果您使用基于密码的认证机制)。将user的值替换为您用户名,将pass的值替换为您密码。如果您的认证机制不需要凭据,则省略连接URI的这一部分。

连接URI的下一部分指定了主机名或IP地址,以及您的MongoDB实例的端口号。在示例中,sample.host代表主机名,而27017是端口号。将这些值替换为您的MongoDB实例。

连接URI的最后一部分包含作为参数的连接选项。示例设置了两个连接选项:maxPoolSize=20w=majority

您可以使用以下连接片段来测试您与Atlas上MongoDB部署的连接。

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驱动程序v4.3及更高版本连接到MongoDB Server v5.0及更高版本时启用此功能。使用此功能时,您可以更新驱动程序或服务器,而无需担心与稳定API涵盖的任何命令的向后兼容性问题。

要了解有关稳定API功能的信息,请参阅服务器手册中的稳定API

您可以通过以下方式连接到本地MongoDB部署

  • 使用无参数的MongoClient对象实例连接到运行在本地主机端口27017的MongoDB服务器

    val mongoClient = MongoClient()
  • 显式指定hostname以连接到指定主机上的MongoDB实例(端口27017

    val mongoClient = MongoClient("mongodb://host1")
  • 显式指定hostnameport

    val mongoClient = MongoClient("mongodb://host1:27017")

要连接到副本集,您必须向MongoClient应用方法指定一个或多个成员。有关副本集的更多信息,请参阅服务器手册中的复制

注意

MongoDB自动发现副本集中的主节点和副节点。

您可以通过指定ConnectionString中的成员来连接到MongoDB副本集。

以下示例显示了如何指定副本集的三个成员

val mongoClient = MongoClient("mongodb://host1:27017,host2:27017,host3:27017")

以下示例显示了如何指定副本集成员和带有副本集名称的replicaSet选项

val mongoClient = MongoClient("mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=myReplicaSet")

以下示例显示了如何指定对应于所有副本集成员的ServerAddress实例的列表

val mongoClient = MongoClient(
MongoClientSettings.builder()
.applyToClusterSettings((builder: ClusterSettings.Builder) => builder.hosts(List(
new ServerAddress("host1", 27017),
new ServerAddress("host2", 27017),
new ServerAddress("host3", 27017)).asJava))
.build())

要连接到分片集群,请在 MongoClient 的 apply 方法中指定 mongos 实例或实例。有关分片集群的更多信息,请参阅服务器手册中的 分片

以下方式可以连接到单个 mongos 实例

  • ConnectionString 中指定主机名和端口号

    val mongoClient = MongoClient( "mongodb://localhost:27017" )
  • 如果 mongoslocalhost:27017 上运行,则省略连接字符串

    val mongoClient = MongoClient()

以下方式可以连接到多个 mongos 实例

  • 指定包含它们的主机名和端口号的 ConnectionString

    val mongoClient = MongoClient("mongodb://host1:27017,host2:27017")
  • 指定对应于每个实例的 ServerAddress 对象列表

    val mongoClient = MongoClient(
    MongoClientSettings.builder()
    .applyToClusterSettings((builder: ClusterSettings.Builder) => builder.hosts(List(
    new ServerAddress("host1", 27017),
    new ServerAddress("host2", 27017)).asJava))
    .build())

您可以使用 ConnectionStringMongoClientSettings 类型,或同时使用这两种方式来指定连接设置。

例如,您可以在连接字符串中指定 TLS/SSL 和身份验证设置

val mongoClient = MongoClient("mongodb://user1:pwd1@host1/?authSource=db1&ssl=true")

您还可以使用 MongoClientSettings 实例来指定 TLS/SSL,并使用 MongoCredential 类型来存储身份验证信息

val user: String = // the user name
val source: String = // the source where the user is defined
val password: Array[Char] = // the password as a character array
// ...
val credential = MongoCredential.createCredential(user, source, password)
val mongoClient: MongoClient = MongoClient(
MongoClientSettings.builder()
.applyToSslSettings((builder: SslSettings.Builder) => builder.enabled(true))
.applyToClusterSettings((builder: ClusterSettings.Builder) => builder.hosts(List(new ServerAddress("host1", 27017)).asJava))
.credential(credential)
.build())

在某些情况下,您可能需要结合连接字符串和程序配置

val connectionString = ConnectionString("mongodb://host1:27107,host2:27017/?ssl=true")
val myCommandListener: CommandListener = ???
val mongoClient = MongoClient(
MongoClientSettings.builder()
.addCommandListener(myCommandListener)
.applyConnectionString(connectionString)
.build())

要了解如何实现其他连接功能,请参阅以下教程

返回

教程