Stable API
注意
Stable API 功能需要 MongoDB Server 5.0 或更高版本。
Overview
在本指南中,您可以了解如何在连接到stable API MongoDB部署时指定 兼容性。
stable API功能会强制服务器以与您指定的API版本兼容的行为来运行操作。 更新驱动程序或服务器时,API 版本会发生变化,这可能会改变这些操作的行为方式。 使用stable API可确保服务器响应一致,并为应用程序提供长期的API稳定性。
以下部分介绍如何为 客户端启用和自定义stable API MongoDB。有关 的更多信息,包括其支持的命令列表,请参阅stable API stable APIMongoDB Server手册中的 。
启用stable API
要启用stable API ,请执行以下步骤:
构造一个
ServerApi
对象并指定stable API版本。 您必须使用ServerApiVersion
枚举中定义的stable API版本。构造一个
MongoClient
对象,为server_api
参数传入ServerApi
对象。
以下代码示例展示了如何指定 Stable API版本 1。选择 Synchronous 或 Asynchronous标签页以查看相应的代码:
from pymongo import MongoClient from pymongo.server_api import ServerApi client = MongoClient("mongodb://<db_username>:<db_password>@<hostname:<port>", server_api=ServerApi("1"))
from pymongo import AsyncMongoClient from pymongo.server_api import ServerApi client = AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname:<port>", server_api=ServerApi("1"))
创建具有指定 API 版本的MongoClient
实例后,使用客户端运行的所有命令都将使用指定版本。 如果您需要使用多个版本的stable API运行命令,请创建一个新的 MongoClient
。
配置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
对象时如何使用这些参数。选择Synchronous或Asynchronous标签页以查看相应的代码:
from pymongo import MongoClient from pymongo.server_api import ServerApi client = MongoClient("mongodb://<db_username>:<db_password>@<hostname:<port>", server_api=ServerApi("1", strict=True, deprecation_errors=True))
from pymongo import AsyncMongoClient from pymongo.server_api import ServerApi client = AsyncMongoClient("mongodb://<db_username>:<db_password>@<hostname:<port>", server_api=ServerApi("1", strict=True, deprecation_errors=True))
故障排除
服务器上无法识别的字段“apiVersion”
如果您指定 API 版本并连接到不支持 Stable API 的 MongoDB 服务器,PyMongo 会引发此异常。 确保您连接到运行 MongoDB Server v 5.0或更高版本的部署。
已提供 apiStrict:true,但命令计数不在 API 版本中
PyMongo如果您的MongoClient
运行的操作不在您指定的stable API 版本中, 会引发此异常。要避免此错误,请使用指定stable API版本支持的替代操作,或在构造 ServerApi
对象时将 strict
选项设置为 False
。
API 文档
有关将stable API与PyMongo使用的更多信息,请参阅以下API文档: