Stable API
Note
The Stable API feature requires MongoDB Server 5.0 or later.
Overview
In this guide, you can learn how to specify Stable API compatibility when connecting to a MongoDB deployment.
The Stable API feature forces the server to run operations with behaviors compatible with the API version you specify. When you update either your library or server version, the API version changes, which can change the way these operations behave. Using the Stable API ensures consistent responses from the server and provides long-term API stability for your application.
The following sections describe how you can enable and customize Stable API for your MongoDB client. For more information about the Stable API, including a list of the commands it supports, see Stable API in the MongoDB Server manual.
Enable the Stable API
To enable the Stable API, perform the following steps:
Construct a
MongoDB\Driver\ServerApi
object and pass the Stable API version you want to use. Currently, the library supports only version 1.Construct a
MongoDB\Client
object. For thedriverOptions
parameter, pass an array that contains theserverApi
option. Set this option to theMongoDB\Driver\ServerApi
object you created in the previous step.
The following code example shows how to specify Stable API version 1:
$uri = "mongodb://<hostname>:<port>"; $driverOptions = ['serverApi' => new MongoDB\Driver\ServerApi('1')]; $client = new MongoDB\Client($uri, [], $driverOptions);
Note
After you create a MongoDB\Client
instance with
a specified API version, all commands you run with the client use the specified
version. If you need to run commands using more than one version of the
Stable API, create a new MongoDB\Client
instance.
Configure the Stable API
The MongoDB\Driver\ServerApi
constructor also accepts the following optional parameters.
You can use these parameters to customize the behavior of the Stable API.
Parameter | Description |
---|---|
strict | Optional. When true , if you call a command that isn't part of
the declared API version, the server raises an exception.Default: null . If this parameter is null, the server applies its default
value of false . |
deprecationErrors | Optional. When true , if you call a command that is deprecated in the
declared API version, the server raises an exception.Default: null . If this parameter is null, the server applies its default
value of false . |
The following code example shows how you can use these parameters when constructing a
MongoDB\Driver\ServerApi
object:
$uri = "mongodb://<hostname>:<port>"; $serverApi = new MongoDB\Driver\ServerApi('1', strict: true, deprecationErrors: true); $driverOptions = ['serverApi' => $serverApi]; $client = new MongoDB\Client($uri, [], $driverOptions);
API Documentation
For more information about the MongoDB\Client
class, see the following PHP library
API documentation:
For more information about the MongoDB\Driver\ServerApi
class, see the following
PHP extension API documentation: