Docs 菜单
Docs 主页
/
连接至 MongoDB

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. 构造一个 mongoc_server_api_t 对象并指定stable API版本。 您必须使用 mongoc_server_api_t 枚举中定义的stable API版本。

  2. 构造一个 mongoc_client_t对象。

  3. 将客户端和 Stable API对象传递给 mongoc_client_set_server_api 函数。

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

#include <mongoc/mongoc.h>
int main ()
{
bson_error_t error;
mongoc_init ();
mongoc_server_api_t *stable_api = mongoc_server_api_new (MONGOC_SERVER_API_V1);
mongoc_client_t *client = mongoc_client_new ("<connection string>");
if (!mongoc_client_set_server_api (client, stable_api, &error))
{
fprintf (stderr, "Failed to set Stable API: %s\n", error.message);
return EXIT_FAILURE;
}
// Use the client for operations...
mongoc_server_api_destroy (stable_api);
mongoc_cleanup ();
return EXIT_SUCCESS;
}

创建具有指定API版本的客户端实例后,使用该客户端运行的所有命令都将使用指定的版本。 如果需要使用多个版本的 Stable API运行命令,请创建一个新客户端。

下表描述了 ServerApi 类的选项。 您可以使用这些选项来自定义 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对象时将两个选项均设立为 true

mongoc_server_api_t *stable_api = mongoc_server_api_new (MONGOC_SERVER_API_V1);
mongoc_server_api_strict (stable_api, true);
mongoc_server_api_deprecation_errors (stable_api, true);
mongoc_client_t *client = mongoc_client_new ("<connection string>");
if (!mongoc_client_set_server_api (client, stable_api, &error)) {
fprintf (stderr, "Failed to set Stable API: %s\n", error.message);
return EXIT_FAILURE;
}

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

在此页面上