Stable API
注意
Stable API 功能需要 MongoDB Server 5.0 或更高版本。
Overview
在本指南中,您可以了解如何在连接到stable API MongoDB部署时指定 兼容性。
stable API功能会强制服务器以与您指定的API版本兼容的行为来运行操作。 更新驱动程序或服务器时,API 版本会发生变化,这可能会改变这些操作的行为方式。 使用stable API可确保服务器响应一致,并为应用程序提供长期的API稳定性。
以下部分介绍如何为 客户端启用和自定义stable API MongoDB。有关 的更多信息,包括其支持的命令列表,请参阅stable API
stable APIMongoDB Server手册中的 。启用stable API
要启用stable API ,请执行以下步骤:
构造一个
mongocxx::options::server_api
对象并指定 Stable API版本。 您必须使用mongocxx::options::server_api::version
枚举中定义的 Stable API版本。 目前,该驾驶员仅支持版本1 (k_version_1
)。构造一个
mongocxx::options::client
对象。 将此对象的server_api_opts
字段设置为您在上一步中创建的server_api
对象。构造一个
mongocxx::client
对象,传入您在上一步中创建的mongocxx::uri
对象和mongocxx::options::client
对象。
以下代码示例展示了如何指定stable API版本 1:
int main() { mongocxx::instance instance; mongocxx::uri uri("mongodb://<hostname>:<port>"); mongocxx::options::server_api server_api_options(mongocxx::options::server_api::version::k_version_1); mongocxx::options::client client_options; client_options.server_api_opts(server_api_options); mongocxx::client client(uri, client_options); }
注意
创建具有指定API版本的mongocxx::client
实例后,使用客户端运行的所有命令都将使用指定版本。 如果需要使用多个版本的 Stable API运行命令,请创建一个新的mongocxx::client
实例。
配置stable API
下表描述了server_api_options
类的属性。 您可以使用这些属性来自定义 Stable API的行为。
选项名称 | 说明 |
---|---|
strict | Optional. When true , if you call a command that isn't part of the declared API version, the driver raises an exception.Default: false |
deprecation_errors | Optional. When true , if you call a command that is deprecated in the declared API version, the driver raises an exception.Default: false |
以下代码示例展示了在构造ServerApi
对象时如何使用这些参数:
int main() { mongocxx::instance instance; mongocxx::uri uri("mongodb://<hostname>:<port>"); mongocxx::options::server_api server_api_options(mongocxx::options::server_api::version::k_version_1); server_api_options.strict(true); server_api_options.deprecation_errors(true); mongocxx::options::client client_options; client_options.server_api_opts(server_api_options); mongocxx::client client(uri, client_options); }
API 文档
有关将 Stable API与C++驾驶员结合使用的更多信息,请参阅以下API文档: