MongoDB\Client::getDatabase()
For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt
MongoDB\Client::getDatabase()
Definition
Gets access to a database on the server. This method is an alias for [MongoDB\Client::selectDatabase()](https://www.mongodb.com/docs/php-library/current/reference/method/mongodbclient-selectdatabase.md#mongodb-phpmethod-phpmethod.MongoDB-Client--selectDatabase-- and will replace it in a future release.
function getDatabase(
string $databaseName,
array $options = []
): MongoDB\Database
Parameters
$databaseName : string
The name of the database to access.
$options : array
An array specifying the desired options.
| Name | Type | Description |
|---|---|---|
| readConcern | MongoDB\Driver\ReadConcern | The default read concern to use for database operations. Defaults to the client's read concern. |
| readPreference | MongoDB\Driver\ReadPreference | The default read preference to use for database operations. Defaults to the client's read preference. |
| typeMap | array | The default type map to use for database operations. Defaults to the client's type map. |
| writeConcern | MongoDB\Driver\WriteConcern | The default write concern to use for database operations. Defaults to the client's write concern. |
Return Values
A [MongoDB\Database](https://www.mongodb.com/docs/php-library/current/reference/class/mongodbdatabase.md#mongodb-phpclass-phpclass.MongoDB-Database object.
Errors/Exceptions
[MongoDB\Exception\InvalidArgumentException](https://www.mongodb.com/docs/php-library/current/reference/exception-classes.md#mongodb-phpclass-phpclass.MongoDB-Exception-InvalidArgumentException for errors related to the parsing of parameters or options.
Behavior
The selected database inherits options such as read preference and type mapping from the [Client](https://www.mongodb.com/docs/php-library/current/reference/class/mongodbclient.md#mongodb-phpclass-phpclass.MongoDB-Client object. Options may be overridden by using the $options parameter.
Example
The following example gets access to the test database:
<?php
$client = new MongoDB\Client;
$db = $client->getDatabase('test');
The following examples gets access to the test database with a custom read preference:
<?php
$client = new MongoDB\Client;
$db = $client->getDatabase(
'test',
[
'readPreference' => new MongoDB\Driver\ReadPreference('primaryPreferred'),
]
);
See Also
-
[
MongoDB\Client::__get()](https://www.mongodb.com/docs/php-library/current/reference/method/mongodbclient__get.md#mongodb-phpmethod-phpmethod.MongoDB-Client--__get-- -
[
MongoDB\Database::__construct()](https://www.mongodb.com/docs/php-library/current/reference/method/mongodbdatabase__construct.md#mongodb-phpmethod-phpmethod.MongoDB-Database--__construct--
