对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
See how MongoDB 9.0 delivers up to 2x higher throughput.
MongoDB Branding Shape
Register now >
Docs 菜单

连接稳定版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. 使用 MongoClient.create() 方法实例化 MongoClient,并将 MongoClientSettings 实例作为参数传递。

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

val serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.build()
// Replace the uri string placeholder with your MongoDB deployment's connection string
val uri = "<connection string>"
val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.serverApi(serverApi)
.build()
val client = MongoClient.create(settings)

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

下表描述了ServerApi类的参数。 您可以使用这些参数自定义stable API的行为。

选项名称
说明

strict

可选.当 True时,如果您调用不属于已声明 API 版本的命令,则驱动程序将引发异常。

默认值:False

deprecationErrors

可选.当 True时,如果您调用在已声明 API 版本中已弃用的命令,则驱动程序将引发异常。

默认值:False

以下代码示例展示了如何通过ServerApi.Builder上的链式方法在ServerApi的实例上设立两个选项:

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

如果您指定 API 版本并连接到不支持 Stable API 的 MongoDB Server,Kotlin Sync 驱动程序会引发此异常。 确保您连接到运行 MongoDB Server v 5.0或更高版本的部署。

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

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