Database Manual / Reference

Stable APIAPI稳定

What is the Stable API, and Should You Use It?什么是稳定的API?你应该使用它吗?

The MongoDB Stable API (previously labeled the Versioned API) lets you upgrade your MongoDB server at will, and ensure that behavior changes between MongoDB versions do not break your application.MongoDB Stable API(之前标记为Versioned API)允许您随意升级MongoDB服务器,并确保MongoDB版本之间的行为变化不会破坏应用程序。

MongoDB 5.0 introduces the Stable API for applications communicating with MongoDB server products. The Stable API allows you to specify which version of the MongoDB API your application runs against.MongoDB 5.0为与MongoDB服务器产品通信的应用程序引入了Stable API。Stable API允许您指定应用程序运行的MongoDB API版本。

The Stable API provides long-term API stability for applications and supports more frequent releases and automatic server upgrades. This allows your applications to take advantage of rapidly released features without risking backwards-breaking changes.稳定的API为应用程序提供了长期的API稳定性,并支持更频繁的发布和服务器自动升级。这使应用程序能够利用快速发布的功能,而不会面临向后破坏更改的风险。

The default behavior for your driver connection will continue to function as expected, even if you do not explicitly specify an apiVersion.即使您没有明确指定apiVersion,驱动程序连接的默认行为也将继续按预期运行。

The Stable API encompasses the subset of MongoDB commands that applications use to read and write data, create collections and indexes, and perform other common tasks.Stable API包含应用程序用来读写数据、创建集合和索引以及执行其他常见任务的MongoDB命令的子集

Note

Starting in February 2022, the "Versioned API" terminology was changed to "Stable API". All concepts and features remain the same with this naming change.从2022年2月开始,“有版本的API”术语更改为“稳定的API”。所有概念和功能在命名更改后保持不变。

Backward Compatibility Guarantee向后兼容性保证

Your application will not experience significant behavior changes resulting from server upgrades. This guarantee holds as long as the new server supports your specified API version.应用程序不会因服务器升级而发生重大行为变化。只要新服务器支持您指定的API版本,此保证就有效。

To guarantee backward compatibility, your application must:为了保证向后兼容性,应用程序必须:

  • Declare an API version声明API版本
  • Only use commands and features supported in your specified API version仅使用指定的API版本中支持的命令和功能
  • Deploy with a supported version of an official driver使用官方驱动程序的支持版本进行部署

Declare the API Version声明API版本


Use the Select your language drop-down menu in the upper-right to set the language of the examples on this page.使用右上角的“选择语言”下拉菜单设置此页面上示例的语言。


To use the Stable API, upgrade to the latest driver and create your application's MongoClient:

MongoDB Shell
mongosh --apiVersion 1
C
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));
C++11
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};
C#
var connectionString = "mongodb://localhost";
var serverApi = new ServerApi(ServerApiVersion.V1);
var mongoClientSettings = MongoClientSettings.FromConnectionString(connectionString);
mongoClientSettings.ServerApi = serverApi;
var mongoClient = new MongoClient(mongoClientSettings);
Go
// 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) }()
}
Java(Sync)
MongoClient client = MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(<connection string>))
.serverApi(
ServerApi.builder()
.version(ServerApiVersion.V1)
.build()
).build()
);

return client;
Kotlin(Coroutine)
val serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.build()

val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString("<connection string>"))
.serverApi(serverApi)
.build()

val client = MongoClient.create(settings)
Motor
    from pymongo.server_api import ServerApi

client = AsyncIOMotorClient(uri, server_api=ServerApi("1"))
Node.js
client = new MongoClient(uri, { serverApi: { version: '1' } });
PHP
$serverApi = new \MongoDB\Driver\ServerApi('1');
$client = new \MongoDB\Client($uriString, [], ['serverApi' => $serverApi]);
Python
from pymongo.server_api import ServerApi

MongoClient(uri, server_api=ServerApi("1"))
RubyRuby
client = Mongo::Client.new(uri_string, server_api: {version: "1"})
Rust
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)?;
Swift(Async)
    let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1)
)
let client = try MongoClient(uri, using: myEventLoopGroup, options: opts)
Swift(Sync)
    let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1)
)
let client = try MongoClient(uri, options: opts)

"1" is currently the only API version available.

By default, clients are non-strict. A non-strict client allows you to run any command, regardless of whether or not it belongs to the Stable API.

Checking Client API Versions

Use the serverStatus command to check for your application's configured API version. For each application connected to your MongoDB instance, an appname appears in the apiVersions document.

See metrics.apiVersions for more information.

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

Create a Strict Client

A strict client rejects all commands outside of the Stable API. Attempts to use commands outside of the Stable API will receive the APIVersionError response.

A strict client also ignores unsupported index types during query planning and execution.

Use the sample code to create a strict client:

MongoDB Shell
mongosh --apiVersion 1 --apiStrict
C
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));
C++11
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};
C#
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);
Go
// 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) }()
}
Java(Sync)
MongoClient client = MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(<connection string>))
.serverApi(
ServerApi.builder()
.version(ServerApiVersion.V1)
.strict(true)
.build()
).build()
);

return client;
Kotlin(Coroutine)
val serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.strict(true)
.build()
Motor
    client = AsyncIOMotorClient(uri, server_api=ServerApi("1", strict=True))
Node.js
client = new MongoClient(uri, { serverApi: { version: '1', strict: true } });
PHP
$serverApi = new \MongoDB\Driver\ServerApi('1', true);
$client = new \MongoDB\Client($uriString, [], ['serverApi' => $serverApi]);
Python
MongoClient(uri, server_api=ServerApi("1", strict=True))
Ruby
client = Mongo::Client.new(uri_string, server_api: {version: "1", strict: true})
Rust
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)?;
Swift(Async)
    let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1, strict: true)
)
let client = try MongoClient(uri, using: myEventLoopGroup, options: opts)
Swift(Sync)
    let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1, strict: true)
)
let client = try MongoClient(uri, options: opts)

Migrate To Stable API Commands移植到稳定的API命令

To migrate your application to use the Stable API, you must:要迁移应用程序以使用Stable API,您必须:

  1. Run your application's test suite with the new MongoClient options.使用新的MongoClient选项运行应用程序的测试套件。
  2. Determine which commands and features you're using that are outside of the Stable API.确定您正在使用的是稳定API之外的命令和功能。
  3. Migrate to alternative commands and features in the Stable API.迁移到Stable API中的替代命令和功能。

Once your application uses only commands and features defined in the Stable API, you can redeploy it with the new MongoClient options and be confident that future server upgrades won't negatively impact your application.一旦应用程序仅使用Stable API中定义的命令和功能,您就可以使用新的MongoClient选项重新部署它,并确信未来的服务器升级不会对应用软件产生负面影响。

How To Use Commands and Features Outside of the Stable API如何在稳定的API之外使用命令和功能

To use commands and features outside of the Stable API, you can connect to your deployment with a non-strict client. By default, clients are non-strict.要使用Stable API之外的命令和功能,可以使用非限制客户端连接到部署。默认情况下,客户端是非严格的。

To create a non-strict client, use the following sample code:要创建非严格客户端,请使用以下示例代码:

MongoDB Shell
mongosh --apiVersion 1
C
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));
C++11
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};
C#
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);
Go
// 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) }()
}
Java(Sync)
MongoClient client = MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(<connection string>))
.serverApi(
ServerApi.builder()
.version(ServerApiVersion.V1)
.strict(false)
.build()
).build()
);
Kotlin(Coroutine)
val serverApi = ServerApi.builder()
.version(ServerApiVersion.V1)
.strict(false)
.build()
Motor
    client = AsyncIOMotorClient(uri, server_api=ServerApi("1", strict=False))
Node.js
client = new MongoClient(uri, { serverApi: { version: '1', strict: false } });
PHP
$serverApi = new \MongoDB\Driver\ServerApi('1', false);
$client = new \MongoDB\Client($uriString, [], ['serverApi' => $serverApi]);
Python
MongoClient(uri, server_api=ServerApi("1", strict=False))
Ruby
client = Mongo::Client.new(uri_string, server_api: {version: "1", strict: false})
Rust
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)?;
Swift(Async)
    let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1, strict: false)
)
let client = try MongoClient(uri, using: myEventLoopGroup, options: opts)
Swift(Sync)
    let opts = MongoClientOptions(
serverAPI: MongoServerAPI(version: .v1, strict: false)
)
let client = try MongoClient(uri, options: opts)

Using this non-strict client allows you to run commands outside of the Stable API. For example, this non-strict client allows you to run the createUser command.使用这个非限制客户端可以在Stable API之外运行命令。例如,这个非严格客户端允许您运行createUser命令。

Important

Commands and features outside of the Stable API do not have the same backward compatibility guarantees as versioned alternatives.Stable API之外的命令和功能与版本化的替代方案没有相同的向后兼容性保证。

Stable API Commands稳定的API命令

The database commands included in Stable API V1 depend on the MongoDB version you are using. To view the database commands included in the Stable API and the MongoDB version they were introduced, see Stable API Changelog.Stable API V1中包含的数据库命令取决于您使用的MongoDB版本。要查看Stable API中包含的数据库命令及其引入的MongoDB版本,请参阅Stable API Changelog

Parameters参数

You can specify the following optional parameters for Stable API in your application's MongoDB driver connection code. Check the MongoDB driver documentation for the driver you use in your application for more information:您可以在应用程序的MongoDB驱动程序连接代码中为Stable API指定以下可选参数。有关更多信息,请查看您在应用程序中使用的驱动程序的MongoDB驱动程序文档:

ParameterType类型Description描述
apiVersionstring字符串Specifies the API Version. "1" is currently the only supported version.指定API版本。"1"是目前唯一受支持的版本。
apiStrictboolean布尔值
If true:如果为true

If you specify apiStrict, you must also specify apiVersion.如果指定apiStrict,则还必须指定apiVersion

If not specified, defaults to false.如果未指定,则默认为false

apiDeprecationErrorsboolean布尔值

If true, using a command or behavior that is deprecated in the specified API version returns an APIDeprecationError. 如果为true,则使用指定API版本中不推荐使用的命令或行为将返回APIDeprecationErrorIf you specify apiDeprecationErrors, you must also specify apiVersion.如果指定apiDeprecationErrors,则还必须指定apiVersion

If not specified, defaults to false.如果未指定,则默认为false

Behavior行为

Parameter Validation参数验证

Starting in MongoDB 5.0, API V1 database commands raise an error if passed a parameter not explicitly accepted by the command.从MongoDB 5.0开始,如果传递了命令未明确接受的参数,API V1数据库命令将引发错误。

Stable API Error Responses稳定的API错误响应

This table shows error responses for problematic Stable API requests.此表显示有问题的Stable API请求的错误响应。

Server Response服务器响应Request请求
APIDeprecationError

Specifies { apiDeprecationErrors: true } with API version V and uses a behavior deprecated in V.

APIStrictError

Specifies { apiStrict: true } with API version V, but uses a behavior not in version V.

APIVersionError

Specifies an apiVersion that the server does not support.

InvalidOptions

Specifies { apiStrict: true } or { apiDeprecationErrors: true } but omits apiVersion.