Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
PHP 库手册
/

选择连接目标

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

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

  • Atlas 集群的 URI

  • 数据库用户名

  • 数据库用户的密码

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

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

以下代码演示了如何使用PHP库连接到Atlas 集群。 该代码还使用serverApi选项来指定 Stable API版本。

<?php
// Replace the placeholder with your Atlas connection string
$uri = '<connection string>';
// Create a MongoDB client with server API options
$client = new MongoDB\Client($uri, [], [
'serverApi' => new MongoDB\Driver\ServerApi('1'),
]);
// Ping the server to verify that the connection works
$admin = $client->admin;
$command = new MongoDB\Driver\Command(['ping' => 1]);
$result = $admin->command($command)->toArray();
echo json_encode($result), PHP_EOL;
echo 'Pinged your deployment. You successfully connected to MongoDB!\n';

提示

按照快速入门的“创建连接string ”步骤检索连接string 。

要连接到本地 MongoDB 部署,请使用localhost作为主机名。 默认情况下, mongod进程在端口27017上运行,但您可以根据部署进行自定义。

以下代码展示了如何使用PHP库连接到本地MongoDB 部署:

<?php
$uri = 'mongodb://localhost:27017';
$uriOptions = ['serverSelectionTimeoutMS' => 10000];
$client = new MongoDB\Client($uri, $uriOptions);

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

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

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

  • false 指定为 directConnection 参数的值。

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

在以下示例中,驱动程序使用样本连接 URI 连接到 MongoDB 副本集 sampleRS,该副本集在三个不同主机(包括 host1)的端口 27017 上运行:

<?php
$uri = 'mongodb://host1:27017/?replicaSet=sampleRS';
// Create a MongoDB client
$client = new MongoDB\Client($uri);

要初始化副本集,必须直接连接到单个成员。 为此,请在连接string中将 directConnection 连接选项设立为 true。 以下代码示例展示了如何设立此连接选项:

<?php
// Replace the placeholders with your actual hostname and port
$uri = 'mongodb://<hostname>:<port>/?directConnection=true';
// Create a MongoDB client
$client = new MongoDB\Client($uri);

注意

Docker 中的副本集

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

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

要使用 DNS 服务发现来查找要连接的服务的 DNS SRV记录,请在连接字符串中指定 SRV 连接格式。 如果指定此格式, PHP库将自动重新扫描新主机。您的部署可以将主机添加到其拓扑结构中,而无需更改客户端配置。

以下代码显示了使用 SRV 连接格式的连接字符串:

$uri = 'mongodb+srv://<hostname>/';

要学习;了解有关 SRV 连接格式的更多信息,请参阅MongoDB Server手册中的 SRV 连接格式条目。

以下代码显示应用程序可能生成的服务器选择错误消息:

No suitable servers found (`serverSelectionTryOnce` set):
[connection refused calling hello on 'a.example.com:27017']
[connection refused calling hello on 'b.example.com:27017']
No suitable servers found: `serverSelectionTimeoutMS` expired:
[socket timeout calling hello on 'example.com:27017']
No suitable servers found: `serverSelectionTimeoutMS` expired:
[connection timeout calling hello on 'a.example.com:27017']
[connection timeout calling hello on 'b.example.com:27017']
[TLS handshake failed: -9806 calling hello on 'c.example.com:27017']
No suitable servers found: `serverselectiontimeoutms` timed out:
[TLS handshake failed: certificate verify failed (64): IP address mismatch calling hello on 'a.example.com:27017']
[TLS handshake failed: certificate verify failed (64): IP address mismatch calling hello on 'b.example.com:27017']

PHP扩展通常将这些错误表示为MongoDB\ 驱动程序\Exception\ConnectionTimeoutException 异常。但是,异常消息源自libmongoc ,即扩展使用的根本的系统库。由于这些消息可以采用多种形式,因此我们建议分解消息的结构,以便更好地诊断应用程序中的错误。

消息通常以“未找到合适的服务器”开头。消息的下一部分指示服务器选择失败的原因。该扩展可避免服务器选择循环,并根据 serverSelectionTryOnce连接字符串选项,默认进行一次尝试。 如果扩展配置为使用循环,则会出现一条包含“serverSelectionTimeoutMS 已过期”短语的消息,表明已用完其时间限制。

消息的最后一个组件告诉我们服务器选择失败的原因,并包括直接来自拓扑结构扫描器的一个或多个错误,拓扑扫描器是负责连接和监控每个托管的服务。之前在监控期间出现错误的任何托管都将包含在此列表中。这些消息通常源自低级套接字或 TLS 函数。

以下列表描述了最后一个错误消息组件中常见短语的可能含义:

  • “连接被拒绝”:远程托管可能并未侦听预期的端口。

  • “连接超时”:可能存在路由问题、防火墙错误或由于延迟导致的超时。

  • “套接字超时”:您可能建立了一个初始连接,但由于延迟而断开或超时。

  • “TLS握手失败”:TLS 或 OCSP 验证未成功,您可能使用了错误配置的 TLS 证书。

如果连接失败,您可以使用 connect 工具获取更多故障排除信息。此工具尝试使用套接字函数连接到连接字符串中的每个托管,然后尝试与数据交互。 如果使用 Composer 安装该库,则可以使用以下命令启动 connect 工具:

php vendor/mongodb/mongodb/tools/connect.php <connection URI>

如果您要连接的服务器不接受连接,则输出类似于以下代码:

Looking up MongoDB at <connection URI>
Found 1 host(s) in the URI. Will attempt to connect to each.
Could not connect to <host>:<port>: Connection refused

注意

该工具仅支持 mongodb:// URI模式。不支持使用 mongodb+srv 方案。

要学习;了解有关使用MongoDB\Client类的更多信息,请参阅以下API文档:

后退

创建客户端

在此页面上