Docs 菜单
Docs 主页
/ / /
PHP 库手册
/

选择连接目标

在此页面上

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

在本指南中,您可以了解如何使用连接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';

提示

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

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

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

<?php
$client = new MongoDB\Client("mongodb://localhost:27017");

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

如果您无法提供副本集主机的完整列表,则可以指定副本集集中的一个或多个主机,并指示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);

要初始化副本集,必须直接连接到单个成员。为此,请在连接字符串中将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);

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

后退

指定连接选项