文档菜单
文档首页
/
MongoDB 手册
/

稳定的API

本页内容

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

MongoDB稳定API(以前称为版本API)允许您随时升级MongoDB服务器,并确保MongoDB版本之间的行为变化不会破坏您的应用程序。

MongoDB 5.0引入了稳定API,用于与MongoDB服务器产品通信的应用程序。稳定API允许您指定应用程序运行的MongoDB API版本。

稳定API为应用程序提供长期API稳定性,支持更频繁的发布和自动服务器升级。这使得您的应用程序可以利用快速发布的功能,而不会风险向后不兼容的更改。

即使您没有明确指定apiVersion.

稳定API包括MongoDB命令的子集,应用程序使用这些命令读取和写入数据,创建集合和索引,以及执行其他常见任务。

注意

从2022年2月开始,“版本API”术语已更改为“稳定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

严格客户端拒绝所有稳定API之外的命令。尝试使用稳定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. 确定您正在使用哪些位于稳定API之外的命令和功能。

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

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

要使用稳定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)

使用这个非严格客户端允许您在稳定API之外运行命令。例如,这个非严格客户端允许您运行createUser命令。

重要

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

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

您可以在应用程序的MongoDB驱动程序连接代码中指定以下可选参数。有关更多信息,请查阅您在应用程序中使用的MongoDB驱动程序文档。

参数
类型
描述
string
指定API版本。目前仅支持版本"1"
boolean
如果true
  • 使用不属于声明API版本的命令将返回一个APIStrictError错误。

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

如果您指定了 apiStrict,则必须也指定 apiVersion

如果未指定,默认为 false

boolean

如果设置为 true,使用指定API版本中已弃用的命令或行为将返回一个 APIDeprecationError。如果您指定了 apiDeprecationErrors,则必须也指定 apiVersion

如果未指定,默认为 false

从MongoDB 5.0版本开始,API V1数据库命令在传递一个命令未明确接受的参数时会引发错误。

此表显示了有问题的稳定API请求的错误响应。

服务器响应
请求

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

指定与API版本V相关的{ apiStrict: true },但使用不在版本V中的行为。

指定服务器不支持的服务版本apiVersion

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

返回

基于插槽的查询执行引擎