对于 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. 构造一个 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

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

deprecation_errors

可选。当true 时,如果您调用在声明的API版本中已弃用的命令,驾驶员将引发异常。默认值: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 文档: