Docs 菜单
Docs 主页
/ / /
Ruby 驱动程序
/

选择连接目标

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

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

  • Atlas 集群的 URL

  • MongoDB 用户名

  • MongoDB 密码

然后,将连接string传递给 Mongo::Client 构造函数。

提示

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

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

以下代码显示了如何使用Ruby驾驶员连接到Atlas 集群。该代码还使用 server_api字段来指定 Stable API版本。

require 'mongo'
# Replace the placeholders with your credentials
uri = "<connection string>"
# Sets the server_api field of the options object to Stable API version 1
options = { server_api: { version: '1' } }
# Creates a new client and connect to the server
client = Mongo::Client.new(uri, options)
# Sends a ping to confirm a successful connection
begin
admin_client = client.use('admin')
result = admin_client.database.command(ping: 1).documents.first
puts "Pinged your deployment. You successfully connected to MongoDB!"
rescue Mongo::Error::OperationFailure => ex
puts ex
ensure
client.close
end

要连接到本地独立运行的MongoDB 部署,请指定服务器的托管。 (可选)指定要连接到的服务器和数据库的端口。如果未指定端口,默认端口为 27017。如果未指定数据库名称,客户端将使用 admin数据库:

Mongo::Client.new([ 'host1:27017' ], database: 'mydb')

您还可以使用连接字符串指定要连接的托管、端口和数据库:

Mongo::Client.new("mongodb://host1:27017/mydb")

您也可以将托管指定为 localhost。以下代码示例连接到默认端口 27017 上的 localhost

client = Mongo::Client.new(["localhost"])

要连接到副本集,建议指定属于副本集的所有节点。在一个或多个节点不可用的事件下,指定所有节点可允许驾驶员在一个节点可用的情况下仍可连接到副本集。

但是,副本集集中任一节点的解决传递给驾驶员就足够了。该节点不一定是主节点 (primary node in the replica set),也可以是隐藏节点。然后,驾驶员将自动发现剩余节点。

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

Mongo::Client.new([ 'host1:27017', 'host2:27018', `host3:21019` ], database: 'mydb')

以下示例展示了如何使用连接字符串连接到副本集:

Mongo::Client.new("mongodb://host1:27017,host2:27018,host3:27019/mydb")

以下示例展示了如何使用 replica_set 选项或 replicaSet连接字符串选项在连接时验证副本集名称:

Mongo::Client.new([ 'host1:27017', 'host2:27018', 'host3:27019' ],
database: 'mydb', replica_set: 'myapp')
# Or by using a connection string:
Mongo::Client.new("mongodb://host1:27017,host2:27018,host3:27019/mydb?replicaSet=myapp")

注意

Docker 中的副本集

当副本集在Docker中运行时,它可能只公开一个MongoDB端点。在这种情况下,无法发现副本集。在连接 URI 中指定 directConnection=false 或未设置此选项,可能会阻止应用程序与之连接。

在测试或开发环境中,您可以通过指定 directConnection=true 来连接到副本集。在生产环境中,我们建议配置集群,以便每个 MongoDB 实例都可以在 Docker 虚拟网络之外访问。

Mongo::Client要学习;了解有关使用Ruby驾驶员创建 对象的更多信息,请参阅 Mongo::Client 的API文档。

后退

Stable API

在此页面上