On this page本页内容
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. MongoDB 5.0为与MongoDB服务器产品通信的应用程序引入了稳定API。The Stable API allows you to specify which version of the MongoDB API your application runs against.稳定API允许您指定应用程序运行的MongoDB API版本。
The Stable API provides long-term API stability for applications and supports more frequent releases and automatic server upgrades. 稳定API为应用程序提供了长期API稳定性,并支持更频繁的发布和自动服务器升级。This allows your applications to take advantage of rapidly released features without risking backwards-breaking changes.这使您的应用程序能够利用快速发布的功能,而不必冒向后破坏更改的风险。
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命令子集。
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”。所有概念和功能与此命名更改保持一致。
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使用支持的官方驱动程序版本进行部署
➤ 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:要使用稳定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(ctx, 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;
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 client = 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"
is currently the only API version available.是目前唯一可用的API版本。
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.默认情况下,客户端是非严格的。非严格客户端允许您运行任何命令,无论它是否属于稳定API。
Use the 使用serverStatus
command to check for your application's configured API version. serverStatus
命令检查应用程序的配置API版本。For each application connected to your MongoDB instance, an 对于连接到MongoDB实例的每个应用程序,appname
appears in the apiVersions
document.apiVersions
文档中都会显示一个appname
。
See metrics.apiVersions for more information.有关详细信息,请参阅metrics.apiVersions
。
db.runCommand( { serverStatus: 1 } ).metrics.apiVersions
A strict client rejects all commands outside of the Stable API. 严格的客户端拒绝Stable API之外的所有命令。Attempts to use commands outside of the Stable API will receive the APIVersionError response.尝试使用Stable API之外的命令将收到APIVersionError响应。
Use the sample code to create a strict client:使用示例代码创建严格的客户端:
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(ctx, 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;
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]);
client = 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)
To migrate your application to use the Stable API, you must:要迁移应用程序以使用稳定API,您必须:
Run your application's test suite with the new MongoClient options.使用新的MongoClient选项运行应用程序的测试套件。
Determine which commands and features you're using that are outside of the Stable API.确定您正在使用的稳定API之外的命令和功能。
Migrate to alternative commands and features in the Stable API.迁移到稳定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选项重新部署它,并确信未来的服务器升级不会对您的应用产生负面影响。
count
MigrationThis example shows how to migrate an application that implements the 此示例演示如何将实现count
command to an alternative method of counting documents. count
命令的应用程序迁移到另一种计算文档的方法。Since the 由于count
command does not belong to the Stable API, this application cannot use the Stable API until the count
command is removed from the code.count
命令不属于Stable API,因此在从代码中删除count
指令之前,此应用程序无法使用Stable API。
Use the sample code to create a 使用示例代码在sales
collection in mongosh
:mongosh
中创建sales
集合:
db.sales.insertMany([ { "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2021-01-01T08:00:00Z") }, { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2021-02-03T09:00:00Z") }, { "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2021-02-03T09:05:00Z") }, { "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2021-02-15T08:00:00Z") }, { "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2021-02-15T09:05:00Z") }, { "_id" : 6, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2021-02-15T12:05:10Z") }, { "_id" : 7, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2021-02-15T14:12:12Z") }, { "_id" : 8, "item" : "abc", "price" : 10, "quantity" : 5, "date" : ISODate("2021-03-16T20:20:13Z") } ])
For example, issuing 例如,发出db.sales.count()
results in this error:db.sales.count()
会导致以下错误:
{ "ok" : 0, "errmsg" : "Provided apiStrict:true, but the command count is not in API Version 1", "code" : 323, "codeName" : "APIStrictError" }
However, the 但是,aggregate
command is in the Stable API and can be used to obtain a count. aggregate
命令位于稳定API中,可以用于获取计数。Use the sample code to obtain a count from the 使用示例代码从sales
collection in mongosh
:mongosh
中的sales
集合中获取计数:
db.sales.aggregate([ { $group: { _id: null, count: { $count: { } } } } ])
This results in a document where the 这将生成一个计数字段包含集合中文档数的文档:count
field contains the number of documents in the collection:
{ "_id" : null, "count" : 8 }
To use commands and features outside of the Stable API, you can connect to your deployment with a non-strict client. 要使用稳定API之外的命令和功能,可以使用非严格客户端连接到部署。By default, clients are non-strict.默认情况下,客户端是非严格的。
Use the sample code to create a non-strict client:使用示例代码创建非严格客户机:
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(ctx, 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() );
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]);
client = 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)
Using this non-strict client allows you to run commands outside of the Stable API. 使用这个非严格客户端允许您在稳定API之外运行命令。For example, this non-strict client now allows you to use the 例如,这个非严格客户端现在允许您再次使用count
command once again.count
命令。
Commands and features outside of the Stable API do not have the same backward compatibility guarantees as versioned alternatives.稳定API之外的命令和功能没有版本化替代方案那样的向后兼容性保证。
API V1 protects you from API-breaking changes for the following commands:API V1保护您免受以下命令的API破坏性更改:
createIndexes
(with limitations) [1]
[1] | (1, 2, 3, 4) |
[2] | explain command will conform to the same format in future API versions.explain 命令的输出在未来的API版本中符合相同的格式。 |
You can specify the following optional parameters for Stable API in your application's MongoDB driver connection code. 您可以在应用程序的MongoDB驱动程序连接代码中为Stable API指定以下可选参数。Check the MongoDB driver documentation for the driver you use in your application for more information:有关更多信息,请查看应用程序中使用的驱动程序的MongoDB驱动程序文档:
Parameter | Type | Description |
---|---|---|
apiVersion | string |
|
apiStrict | boolean |
|
apiDeprecationErrors | boolean |
|
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数据库命令传递了命令未明确接受的参数,则会引发错误。
In MongoDB 4.4 and earlier, unrecognized parameters are silently ignored.在MongoDB 4.4及更早版本中,未识别的参数被自动忽略。
This table shows error responses for problematic Stable API requests.此表显示了有问题的稳定API请求的错误响应。
APIDeprecationError |
|
APIStrictError |
|
APIVersionError |
|
InvalidOptions |
|