对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

Stable API

注意

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

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

Stable API功能会强制服务器以与您指定的API版本兼容的行为来运行操作。 使用 Stable API可确保服务器响应一致,并为应用程序提供长期的API稳定性。

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

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

  1. 构造一个 ServerApi 对象并指定stable API版本。 您必须使用 ServerApiVersion 枚举中定义的stable API版本。

  2. 使用MongoClientSettings.Builder类构造一个MongoClientSettings对象。

  3. 使用 MongoClients.create() 方法实例化 MongoClient,并将 MongoClientSettings 实例作为参数传递。

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

ServerApi serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.build();
// Replace the placeholder with your Atlas connection string
String uri = "<connection string URI>";
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(uri))
.serverApi(serverApi)
.build();
try (MongoClient mongoClient = MongoClients.create(settings)) {
// Perform client operations here
}

使用 Stable API创建MongoClient实例后,使用客户端运行的所有命令都将使用指定的 Stable API配置。 如果必须使用备用配置运行命令,请创建新的MongoClient

下表描述了ServerApi.Builder类的可链式方法,您可以使用这些方法自定义 Stable API的行为。

选项名称
说明

strict()

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

deprecationErrors()

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

以下代码示例展示了如何通过在ServerApi.Builder上链接方法来配置ServerApi的实例:

ServerApi serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.strict(true)
.deprecationErrors(true)
.build();

如果您指定API版本并连接到不支持Stable API 的MongoDB服务器,Java Reactive Streams驱动程序会引发此异常。确保您要连接到运行MongoDB Server v5.0 或更高版本的部署。

如果您的 MongoClient 运行的操作不在您指定的 Stable API 版本中,则 Java Reactive Streams 驱动程序会引发此异常。要避免此错误,请使用指定 Stable API 版本支持的替代操作,或在构造 ServerApi 对象时将 strict 选项设立为 False

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