Docs 菜单
Docs 主页
/ / /
Scala
/

选择连接目标

在此页面上

  • Overview
  • Atlas
  • 本地部署
  • 副本集
  • API 文档

在本指南中,您可以学习;了解如何使用连接string和 MongoClient对象连接到不同类型的MongoDB部署。

要连接到MongoDB 上的Atlas 部署,请在连接string 中包含以下元素:

  • Atlas 集群的URL

  • 您的 MongoDB 用户名

  • 您的MongoDB密码

然后,将连接string传递给 MongoClient 构造函数。

提示

按照 Atlas驱动程序连接指南检索连接string 。

当您连接到Atlas时,我们建议使用 Stable API客户端选项,以避免Atlas升级到新版本的MongoDB Server时发生重大更改。 要学习;了解有关 Stable API功能的更多信息,请参阅 Stable API指南。

以下代码显示了如何使用Scala驾驶员连接到Atlas 集群。该代码还使用 serverApi() 方法指定 Stable API版本。

object MongoClientConnectToAtlas {
def main(args: Array[String]): Unit = {
// Replace the placeholder with your Atlas connection string
val connectionString = "<connection string>";
// Constructs 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()
// Creates a new client and connects to the server
Using(MongoClient(settings)) { mongoClient =>
// Sends 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!")
}
}
}

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

  • 实例化一个不带任何参数的 MongoClient对象,以连接到在 localhost 上运行的MongoDB服务器的27017 端口:

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

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

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

要连接到副本集,请指定副本集节点的主机名(或IP地址)和端口号。

如果您无法提供副本集集中主机的完整列表,则可以指定副本集集中的一个或多个主机,并指示Scala驾驶员执行自动发现以查找其他主机。要指示驾驶员执行自动发现,请执行以下操作之一:

  • 将副本集的名称指定为 replicaSet 参数的值。

  • false 指定为 directConnection 参数的值。

  • 在副本集中指定多个主机。

您可以通过在 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构造函数是非阻塞的。 连接到副本集时,构造函数会立即返回,而客户端会使用后台线程连接到副本集。

如果构造 MongoClient 并立即打印其 nodes 属性的string表示形式,则当客户端连接到副本集成员时,列表可能为空。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

后退

Stable API