Stable API
注意
Stable API功能需要MongoDB Server 6.0 或更高版本。
Overview
在本指南中,您可以了解如何在连接到stable API MongoDB部署时指定 兼容性。
Stable API功能会强制服务器以与您指定的API版本兼容的行为来运行操作。 更新库或服务器版本时, API版本会发生变化,这可能会改变这些操作的行为方式。 使用 Stable API可确保服务器响应一致,并为应用程序提供长期的API稳定性。
以下部分介绍如何为 客户端启用和自定义stable API MongoDB。有关 的更多信息,包括其支持的命令列表,请参阅stable API stable APIMongoDB Server手册中的 。
启用stable API
要启用stable API ,请执行以下步骤:
构造一个
MongoDB\Driver\ServerApi
对象并传递您要使用的 Stable API版本。 目前,该库仅支持版本1 。构造一个
MongoDB\Client
对象。 对于driverOptions
参数,请传递一个包含serverApi
选项的大量。 将此选项设置为您在上一步中创建的MongoDB\Driver\ServerApi
对象。
以下代码示例展示了如何指定stable API版本 1:
$uri = "mongodb://<hostname>:<port>"; $driverOptions = ['serverApi' => new MongoDB\Driver\ServerApi('1')]; $client = new MongoDB\Client($uri, [], $driverOptions);
注意
创建具有指定API版本的MongoDB\Client
实例后,使用客户端运行的所有命令都将使用指定版本。 如果需要使用多个版本的 Stable API运行命令,请创建一个新的MongoDB\Client
实例。
配置stable API
MongoDB\Driver\ServerApi
构造函数还接受以下可选参数。 您可以使用这些参数来自定义 Stable API的行为。
Parameter | 说明 |
---|---|
strict | Optional. When true , if you call a command that isn't part of
the declared API version, the server raises an exception.Default: null . If this parameter is null, the server applies its default
value of false . |
deprecationErrors | Optional. When true , if you call a command that is deprecated in the
declared API version, the server raises an exception.Default: null . If this parameter is null, the server applies its default
value of false . |
以下代码示例展示了在构造MongoDB\Driver\ServerApi
对象时如何使用这些参数:
$uri = "mongodb://<hostname>:<port>"; $serverApi = new MongoDB\Driver\ServerApi('1', strict: true, deprecationErrors: true); $driverOptions = ['serverApi' => $serverApi]; $client = new MongoDB\Client($uri, [], $driverOptions);
API 文档
有关MongoDB\Client
类的更多信息,请参阅以下PHP库API文档:
有关MongoDB\Driver\ServerApi
类的更多信息,请参阅以下PHP扩展API文档: