对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
MongoDB Branding Shape
Click here >
Docs 菜单

Stable API

注意

Stable API 功能需要 MongoDB Server 5.0 或更高版本。

在本指南中,您可以了解如何在连接到stable API MongoDB部署时指定 兼容性。

stable API功能会强制服务器以与您指定的API版本兼容的行为来运行操作。 更新驱动程序或服务器时,API 版本会发生变化,这可能会改变这些操作的行为方式。 使用stable API可确保服务器响应一致,并为应用程序提供长期的API稳定性。

以下部分介绍如何为 客户端启用和自定义stable API MongoDB。有关stable API 的更多信息,包括其支持的命令列表,请参阅stable APIMongoDB Server 手册中的 。

要启用stable API ,请执行以下步骤:

  1. 构造一个 mongocxx::options::server_api对象并指定 Stable API版本。您必须使用 mongocxx::options::server_api::version枚举中定义的 Stable API 版本。目前,该驱动程序仅支持版本 1 (k_version_1)。

  2. 构造一个mongocxx::options::client对象。 将此对象的server_api_opts字段设置为您在上一步中创建的server_api对象。

  3. 构造一个mongocxx::client对象,传入您在上一步中创建的mongocxx::uri对象和mongocxx::options::client对象。

以下代码示例展示了如何指定stable API版本 1:

#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/client.hpp>
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实例。

下表描述了server_api_options类的属性。 您可以使用这些属性来自定义 Stable API的行为。

选项名称
说明

strict

可选。当true 时,如果您调用不属于已声明API版本的命令,驾驶员将引发异常。默认值:

false

deprecation_errors

可选。当true 时,如果您调用在声明的API版本中已弃用的命令,驾驶员将引发异常。默认值:

false

以下代码示例展示了在构造ServerApi对象时如何使用这些参数:

#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/client.hpp>
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);
}

有关将 Stable API 与 C++ 驱动程序结合使用的更多信息,请参阅以下 API 文档: