Docs 菜单
Docs 主页
/
MongoDB Manual
/

Stable API

在此页面上

  • 什么是 Stable API 以及是否应使用它?
  • 向后兼容性保证
  • 声明 API 版本
  • 检查客户端 API 版本
  • 创建严格的客户端
  • 迁移到稳定版 API 命令
  • 如何使用 Stable API 之外的命令和功能
  • Stable API 命令
  • 参数
  • 行为
  • Stable API 错误响应

MongoDB Stable API(以前标记为 Versioned API)允许随意升级 MongoDB Server,并确保不同 MongoDB 版本之间的行为更改不会破坏您的应用程序。

MongoDB 5.0 将引入 Stable API,以便应用程序与 MongoDB Server 产品进行通信。Stable API 允许指定应用程序要对其运行的 MongoDB API 版本。

Stable API 可为应用程序提供长期 API 稳定性,并支持更频繁的发布和自动服务器升级。如此一来,您的应用程序便可利用快速发布的功能,而无需冒险执行会破坏向后兼容性的更改。

即使您未显式指定 apiVersion,驱动程序连接的默认行为仍会继续按预期运行。

Stable API 包含应用程序用于读写数据、创建集合和索引以及执行其他常见任务的部分 MongoDB 命令

注意

从 2022 年 2 月开始,“版本化 API”术语更改为“Stable API”。此次命名更改后,所有概念和功能均保持不变。

您的应用程序不会因服务器升级而发生重大行为变化。只要新服务器支持您指定的 API 版本,该保证就有效。

为保证向后兼容性,应用程序必须:

  • 声明 API 版本

  • 只能使用指定 API 版本支持的命令和功能

  • 使用受支持的官方驱动程序版本进行部署


➤ 使用右上角的选择语言下拉菜单来设置本页面上示例的语言。


要使用稳定版 API,请升级到最新的驱动程序并创建应用程序的 MongoClient:

mongosh --apiVersion 1
mongoc_client_t *client = NULL;
mongoc_server_api_t *server_api = NULL;
mongoc_server_api_version_t server_api_version;
bson_error_t error;
/* For a replica set, include the replica set name and a seedlist of the
* members in the URI string; e.g.
* uri_repl = "mongodb://mongodb0.example.com:27017,mongodb1.example.com:" \
* "27017/?replicaSet=myRepl";
* client = mongoc_client_new (uri_repl);
* For a sharded cluster, connect to the mongos instances; e.g.
* uri_sharded =
* "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/";
* client = mongoc_client_new (uri_sharded);
*/
/* Create a mongoc_client_t without server API options configured. */
client = get_client_for_version_api_example ();
mongoc_server_api_version_from_string ("1", &server_api_version);
server_api = mongoc_server_api_new (server_api_version);
assert (mongoc_client_set_server_api (client, server_api, &error));
using namespace mongocxx;
uri client_uri{"mongodb://localhost"};
// Create an option set for API v1
const auto server_api_opts =
options::server_api{options::server_api::version_from_string("1")};
// Store it in the set of client options
const auto client_opts =
options::client{}
.server_api_opts(server_api_opts); // Set the version
// Create a new client with the options
mongocxx::client client{client_uri, client_opts};
var connectionString = "mongodb://localhost";
var serverApi = new ServerApi(ServerApiVersion.V1);
var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString);
mongoClientSettings.ServerApi = serverApi;
var mongoClient = new MongoClient(mongoClientSettings);
// StableAPIExample is an example of creating a client with stable API.
func StableAPIExample() {
ctx := context.TODO()
// For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
// uri := "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl"
// For a sharded cluster, connect to the mongos instances; e.g.
// uri := "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/"
uri := mtest.ClusterURI()
serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1)
clientOpts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPIOptions)
client, err := mongo.Connect(clientOpts)
if err != nil {
panic(err)
}
defer func() { _ = client.Disconnect(ctx) }()
}
MongoClient client = MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(<connection string>))
.serverApi(
ServerApi.builder()
.version(ServerApiVersion.V1)
.build()
).build()
);
return client;
val serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.build()
val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString("<connection string>"))
.serverApi(serverApi)
.build()
val client = MongoClient.create(settings)
from pymongo.server_api import ServerApi
client = AsyncIOMotorClient(uri, server_api=ServerApi("1"))
client = new MongoClient(uri, { serverApi: { version: '1' } });
$serverApi = new \MongoDB\Driver\ServerApi('1');
$client = new \MongoDB\Client($uriString, [], ['serverApi' => $serverApi]);
from pymongo.server_api import ServerApi
MongoClient(uri, server_api=ServerApi("1"))
client = Mongo::Client.new(uri_string, server_api: {version: "1"})
let mut options = ClientOptions::parse(&uri).await?;
let server_api = ServerApi::builder().version(ServerApiVersion::V1).build();
options.server_api = Some(server_api);
let client = Client::with_options(options)?;
let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1)
)
let client = try MongoClient(uri, using: myEventLoopGroup, options: opts)
let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1)
)
let client = try MongoClient(uri, options: opts)

"1" 是目前唯一可用的 API 版本。

默认情况下,客户端是 非严格的。 非严格客户端允许您运行任何命令,无论它是否属于稳定 API。

使用 serverStatus 命令检查是否存在应用程序的已配置 API 版本。对于连接到 MongoDB 实例的每个应用程序,apiVersions 文档中均会显示一个 appname

有关更多信息,请参阅 metrics.apiVersions

db.runCommand( { serverStatus: 1 } ).metrics.apiVersions

严格的客户端会拒绝 Stable API 之外的所有命令。尝试使用 Stable API 之外的命令会收到 APIVersionError 响应。

严格客户端还会在查询规划和执行期间忽略不支持的索引类型。

使用示例代码创建严格的客户端:

mongosh --apiVersion 1 --apiStrict
mongoc_client_t *client = NULL;
mongoc_server_api_t *server_api = NULL;
mongoc_server_api_version_t server_api_version;
bson_error_t error;
/* For a replica set, include the replica set name and a seedlist of the
* members in the URI string; e.g.
* uri_repl = "mongodb://mongodb0.example.com:27017,mongodb1.example.com:" \
* "27017/?replicaSet=myRepl";
* client = mongoc_client_new (uri_repl);
* For a sharded cluster, connect to the mongos instances; e.g.
* uri_sharded =
* "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/";
* client = mongoc_client_new (uri_sharded);
*/
/* Create a mongoc_client_t without server API options configured. */
client = get_client_for_version_api_example ();
mongoc_server_api_version_from_string ("1", &server_api_version);
server_api = mongoc_server_api_new (server_api_version);
mongoc_server_api_strict (server_api, true);
assert (mongoc_client_set_server_api (client, server_api, &error));
using namespace mongocxx;
uri client_uri{"mongodb://localhost"};
// Create an option set for API v1
const auto server_api_opts =
options::server_api{options::server_api::version_from_string("1")}
.strict(true); // Enable strict mode for the server API
// Store it in the set of client options
const auto client_opts =
options::client{}
.server_api_opts(server_api_opts); // Set the version and options
// Create a new client with the options
mongocxx::client client{client_uri, client_opts};
var connectionString = "mongodb://localhost";
var serverApi = new ServerApi(ServerApiVersion.V1, strict: true);
var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString);
mongoClientSettings.ServerApi = serverApi;
var mongoClient = new MongoClient(mongoClientSettings);
// StableAPIStrictExample is an example of creating a client with strict stable API.
func StableAPIStrictExample() {
ctx := context.TODO()
// For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
// uri := "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl"
// For a sharded cluster, connect to the mongos instances; e.g.
// uri := "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/"
uri := mtest.ClusterURI()
serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1).SetStrict(true)
clientOpts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPIOptions)
client, err := mongo.Connect(clientOpts)
if err != nil {
panic(err)
}
defer func() { _ = client.Disconnect(ctx) }()
}
MongoClient client = MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(<connection string>))
.serverApi(
ServerApi.builder()
.version(ServerApiVersion.V1)
.strict(true)
.build()
).build()
);
return client;
val serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.strict(true)
.build()
client = AsyncIOMotorClient(uri, server_api=ServerApi("1", strict=True))
client = new MongoClient(uri, { serverApi: { version: '1', strict: true } });
$serverApi = new \MongoDB\Driver\ServerApi('1', true);
$client = new \MongoDB\Client($uriString, [], ['serverApi' => $serverApi]);
MongoClient(uri, server_api=ServerApi("1", strict=True))
client = Mongo::Client.new(uri_string, server_api: {version: "1", strict: true})
let mut options = ClientOptions::parse(&uri).await?;
let server_api = ServerApi::builder()
.version(ServerApiVersion::V1)
.strict(true)
.build();
options.server_api = Some(server_api);
let client = Client::with_options(options)?;
let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1, strict: true)
)
let client = try MongoClient(uri, using: myEventLoopGroup, options: opts)
let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1, strict: true)
)
let client = try MongoClient(uri, options: opts)

要迁移应用程序以使用稳定版 API,您必须:

  1. 使用新的 MongoClient 选项运行应用程序的测试套件。

  2. 确定您正在使用的哪些命令和功能不属于 Stable API。

  3. 迁移到稳定 API 中的替代命令和功能。

一旦您的应用程序仅使用 Stable API 中定义的命令和功能,便可使用新的 MongoClient 选项重新部署它,并确信未来的服务器升级不会对您的应用程序产生负面影响。

要使用 Stable API 之外的命令和功能,可使用非严格客户端连接到您的部署。默认情况下,客户端为非严格客户端。

要创建非严格客户端,请使用以下示例代码:

mongosh --apiVersion 1
mongoc_client_t *client = NULL;
mongoc_server_api_t *server_api = NULL;
mongoc_server_api_version_t server_api_version;
bson_error_t error;
/* For a replica set, include the replica set name and a seedlist of the
* members in the URI string; e.g.
* uri_repl = "mongodb://mongodb0.example.com:27017,mongodb1.example.com:" \
* "27017/?replicaSet=myRepl";
* client = mongoc_client_new (uri_repl);
* For a sharded cluster, connect to the mongos instances; e.g.
* uri_sharded =
* "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/";
* client = mongoc_client_new (uri_sharded);
*/
/* Create a mongoc_client_t without server API options configured. */
client = get_client_for_version_api_example ();
mongoc_server_api_version_from_string ("1", &server_api_version);
server_api = mongoc_server_api_new (server_api_version);
mongoc_server_api_strict (server_api, false);
assert (mongoc_client_set_server_api (client, server_api, &error));
using namespace mongocxx;
uri client_uri{"mongodb://localhost"};
// Create an option set for API v1
const auto server_api_opts =
options::server_api{options::server_api::version_from_string("1")}
.strict(false); // Explicitly disable strict mode for the server API
// Store it in the set of client options
const auto client_opts =
options::client{}
.server_api_opts(server_api_opts); // Set the version and options
// Create a new client with the options
mongocxx::client client{client_uri, client_opts};
var connectionString = "mongodb://localhost";
var serverApi = new ServerApi(ServerApiVersion.V1, strict: false);
var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString);
mongoClientSettings.ServerApi = serverApi;
var mongoClient = new MongoClient(mongoClientSettings);
// StableAPINonStrictExample is an example of creating a client with non-strict stable API.
func StableAPINonStrictExample() {
ctx := context.TODO()
// For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g.
// uri := "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl"
// For a sharded cluster, connect to the mongos instances; e.g.
// uri := "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/"
uri := mtest.ClusterURI()
serverAPIOptions := options.ServerAPI(options.ServerAPIVersion1).SetStrict(false)
clientOpts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPIOptions)
client, err := mongo.Connect(clientOpts)
if err != nil {
panic(err)
}
defer func() { _ = client.Disconnect(ctx) }()
}
MongoClient client = MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(<connection string>))
.serverApi(
ServerApi.builder()
.version(ServerApiVersion.V1)
.strict(false)
.build()
).build()
);
val serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.strict(false)
.build()
client = AsyncIOMotorClient(uri, server_api=ServerApi("1", strict=False))
client = new MongoClient(uri, { serverApi: { version: '1', strict: false } });
$serverApi = new \MongoDB\Driver\ServerApi('1', false);
$client = new \MongoDB\Client($uriString, [], ['serverApi' => $serverApi]);
MongoClient(uri, server_api=ServerApi("1", strict=False))
client = Mongo::Client.new(uri_string, server_api: {version: "1", strict: false})
let mut options = ClientOptions::parse(&uri).await?;
let server_api = ServerApi::builder()
.version(ServerApiVersion::V1)
.strict(false)
.build();
options.server_api = Some(server_api);
let client = Client::with_options(options)?;
let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1, strict: false)
)
let client = try MongoClient(uri, using: myEventLoopGroup, options: opts)
let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1, strict: false)
)
let client = try MongoClient(uri, options: opts)

通过使用此非严格客户端,可运行 Stable API 之外的命令。例如,此非严格客户端允许运行 createUser 命令。

重要

Stable API 之外的命令和功能没有与版本化替代方案相同的向后兼容性保证。

Stable API V1 中包含的数据库命令取决于您使用的 MongoDB 版本。要查看 Stable API 中包含的数据库命令及其引入的 MongoDB 版本,请参阅 Stable API 变更日志

您可以在应用程序的 MongoDB 驱动程序连接代码中为 Stable API 指定以下可选参数。如需获取更多信息,请查看您在应用程序中使用的驱动程序的 MongoDB 驱动程序文档:

Parameter
类型
说明
字符串
指定 API 版本。"1" 是目前唯一支持的版本。
布尔
如果为 true
  • 使用不属于已声明 API 版本的命令会返回 APIStrictError 错误。

  • 查询规划 器会忽略 Stable API 不支持 的索引。

如果指定 apiStrict ,则还须指定 apiVersion

如果未指定,则默认为 false

布尔

如果为 true,则使用指定 API 版本中已废弃的命令或行为会返回 APIDeprecationError。如果指定 apiDeprecationErrors,则还须指定 apiVersion

如果未指定,则默认为 false

从 MongoDB 5.0 开始,如果传递的参数未被命令显式接受,则 API V1 数据库命令会引发错误。

此表显示了针对有问题 Stable API 请求的错误响应。

服务器响应
请求

指定 API 版本为 V{ apiDeprecationErrors: true },并使用 V 中已弃用的行为。

指定 API 版本为 V{ apiStrict: true },但使用 V 版本之外的行为。

指定服务器不支持的 apiVersion

指定 { apiStrict: true }{ apiDeprecationErrors: true },但省略 apiVersion

后退

请参阅:基于插槽的查询执行引擎