Connect php and mongodb

MongoDB\Client::__construct()

Optional. The URI of the standalone, replica set, or sharded cluster to which to connect. Refer to Connection String URI Format in the MongoDB manual for more information.

Defaults to «mongodb://127.0.0.1:27017» if unspecified.

Any special characters in the URI components need to be encoded according to RFC 3986. This is particularly relevant to the username and password, which can often include special characters such as @ , : , or % . When connecting via a Unix domain socket, the socket path may contain special characters such as slashes and must be encoded. The rawurlencode() function may be used to encode constituent parts of the URI.

Optional. Specifies additional URI options, such as authentication credentials or query string parameters. The options specified in $uriOptions take precedence over any analogous options present in the $uri string and do not need to be encoded according to RFC 3986.

Refer to the MongoDB\Driver\Manager::__construct() extension reference and MongoDB connection string documentation for accepted options.

The $driverOptions parameter supports the following options:

Optional. Options to configure client-side field-level encryption in the driver. The encryption options are documented in the extension documentation. For the keyVaultClient option, you may pass a MongoDB\Client instance, which will be unwrapped to provide a MongoDB\Driver\Manager to the extension.

Читайте также:  Exit running python script

Optional. Additional driver metadata to be passed on to the server handshake. This is an array containing name , version , and platform fields:

[ 'name' => 'my-driver', 'version' => '1.2.3-dev', 'platform' => 'some-platform', ] 

This feature is primarily designed for custom drivers and ODMs, which may want to identify themselves to the server for diagnostic purposes. Applications should use the appName URI option instead of driver metadata.

Optional. Used to declare an API version on the client. See the Stable API tutorial for usage.

Optional. Default type map to apply to cursors, which determines how BSON documents are converted to PHP values. The MongoDB PHP Library uses the following type map by default:

[ 'array' => 'MongoDB\Model\BSONArray', 'document' => 'MongoDB\Model\BSONDocument', 'root' => 'MongoDB\Model\BSONDocument', ] 

Optional. Disables hostname validation if true . Defaults to false .

Allowing invalid hostnames may expose the driver to a man-in-the-middle attack.

Deprecated since version 1.6: This option has been deprecated. Use the tlsAllowInvalidHostnames URI option instead.

Optional. Path to a correctly hashed certificate directory. The system certificate store will be used by default.

Falls back to the deprecated capath SSL context option if not specified.

Optional. Path to a certificate authority file. The system certificate store will be used by default.

Falls back to the deprecated cafile SSL context option if not specified.

Deprecated since version 1.6: This option has been deprecated. Use the tlsCAFile URI option instead.

Optional. Path to a PEM encoded certificate to use for client authentication.

Falls back to the deprecated local_cert SSL context option if not specified.

Deprecated since version 1.6: This option has been deprecated. Use the tlsCertificateKeyFile URI option instead.

Optional. Passphrase for the PEM encoded certificate (if applicable).

Falls back to the deprecated passphrase SSL context option if not specified.

Deprecated since version 1.6: This option has been deprecated. Use the tlsCertificateKeyFilePassword URI option instead.

Optional. Disables certificate validation true . Defaults to false .

Falls back to the deprecated allow_self_signed SSL context option if not specified.

Deprecated since version 1.6: This option has been deprecated. Use the tlsAllowInvalidCertificates URI option instead.

Optional. SSL context options to be used as fallbacks for other driver options (as specified). Note that the driver does not consult the default stream context.

This option is supported for backwards compatibility, but should be considered deprecated.

Errors/Exceptions

MongoDB\Exception\InvalidArgumentException for errors related to the parsing of parameters or options.

MongoDB\Driver\Exception\InvalidArgumentException for errors related to the parsing of parameters or options at the driver level.

MongoDB\Driver\Exception\RuntimeException for other errors at the driver level (e.g. connection errors).

Behavior

A MongoDB\Driver\Manager is constructed internally. Per the Server Discovery and Monitoring specification, MongoDB\Driver\Manager::__construct() performs no I/O. Connections will be initialized on demand, when the first operation is executed.

Examples

Connecting to a Standalone server

If you do not specify a $uri value, the driver connects to a standalone mongod on 127.0.0.1 via port 27017 . To connect to a different server, pass the corresponding connection string as the first parameter when creating the Client instance:

 $client = new MongoDB\Client('mongodb://mongodb-deployment:27017'); 

Connecting to a Replica Set

The following example demonstrates how to connect to a replica set with a custom read preference:

 $client = new MongoDB\Client( 'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet', [ 'readPreference' => 'secondaryPreferred', ] ); 

Connecting with SSL and Authentication

The following example demonstrates how to connect to a MongoDB replica set with SSL and authentication, as is used for MongoDB Atlas:

 $client = new MongoDB\Client( 'mongodb://myUsername:myPassword@rs1.example.com,rs2.example.com/?ssl=true&replicaSet=myReplicaSet&authSource=admin' ); 

Alternatively, the authentication credentials and URI parameters may be specified in the constructor’s $uriOptions parameter:

 $client = new MongoDB\Client( 'mongodb://rs1.example.com,rs2.example.com/' [ 'username' => 'myUsername', 'password' => 'myPassword', 'ssl' => true, 'replicaSet' => 'myReplicaSet', 'authSource' => 'admin', ], ); 

The driver supports additional SSL options, which may be specified in the constructor’s $driverOptions parameter. Those options are covered in the MongoDB\Driver\Manager::__construct() documentation.

Specifying a Custom Type Map

By default, the MongoDB PHP Library deserializes BSON documents and arrays as MongoDB\Model\BSONDocument and MongoDB\Model\BSONArray objects, respectively. The following example demonstrates how to have the library unserialize everything as a PHP array, as was done in the legacy mongo extension.

 $client = new MongoDB\Client( null, [], [ 'typeMap' => [ 'root' => 'array', 'document' => 'array', 'array' => 'array', ], ] ); 

See Also

© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.

Источник

MongoDB PHP Driver

Welcome to the documentation site for the official MongoDB PHP driver. You can add the driver to your application to work with MongoDB in PHP. The MongoDB PHP Driver consists of the two following components:

While it is possible to use the extension alone, MongoDB recommends using both the extension and the library together. Download the components you need or set up a runnable project by following our tutorials.

Installation

First, make sure you have a recent version of PHP installed on your system. See the official PHP manual

for download and installation instructions.

Install the PHP MongoDB Extension before installing the PHP Library for MongoDB. You can install the extension using PECL

$ sudo pecl install mongodb

Finally, add the following line to your php.ini file:

Note

On some systems, there may be multiple INI files for individual SAPIs (e.g. CLI, FPM). Make sure to enable the extension in all SAPIs that you need.

The preferred method of installing the PHP library is with Composer

by running the following from your project root:

$ composer require mongodb/mongodb

Once you have installed the library, ensure that your application includes Composer’s autoloader as in the following example:

require_once __DIR__ . '/vendor/autoload.php';

Additional installation instructions may be found in the library documentation .

Connect to MongoDB Atlas

You can use the following connection snippet to test your connection to your MongoDB deployment on Atlas:

use Exception;
use MongoDB\Client;
use MongoDB\Driver\ServerApi;
// Replace the placeholder with your Atlas connection string
$uri = '';
// Specify Stable API version 1
$apiVersion = new ServerApi(ServerApi::V1);
// Create a new client and connect to the server
$client = new MongoDB\Client($uri, [], ['serverApi' => $apiVersion]) ;
try
// Send a ping to confirm a successful connection
$client->selectDatabase('admin') ->command(['ping' => 1]) ;
echo "Pinged your deployment. You successfully connected to MongoDB!\n";
> catch (Exception $e)
printf($e->getMessage() ) ;
>

This connection snippet uses the Stable API feature, which you can enable when using the PHP driver v1.9 and later to connect to MongoDB Server v5.0 and later. When you use this feature, you can update your driver or server without worrying about backward compatibility issues with any commands covered by the Stable API.

To learn more about the Stable API feature, see Stable API in the Server manual.

Note

Starting from Feburary 2022, the Versioned API is known as the Stable API. All concepts and features remain the same with this naming change.

Connect to MongoDB Atlas Without the Stable API

If you are using a version of MongoDB or the driver that doesn’t support the Stable API feature, you can use the following code snippet to test your connection to your MongoDB deployment on Atlas:

use Exception;
use MongoDB\Client;
// Replace the placeholder with your Atlas connection string
$uri = '';
// Create a new client and connect to the server
$client = new MongoDB\Client($uri) ;
try
// Send a ping to confirm a successful connection
$client->selectDatabase('admin') ->command(['ping' => 1]) ;
echo "Pinged your deployment. You successfully connected to MongoDB!\n";
> catch (Exception $e)
printf($e->getMessage() ) ;
>

Connect to a MongoDB Server on Your Local Machine

If you need to run a MongoDB server on your local machine for development purposes instead of using an Atlas cluster, you need to complete the following:

Important

Always secure your MongoDB server from malicious attacks. See our Security Checklist for a list of security recommendations.

After you successfully start your MongoDB server, specify your connection string in your driver connection code.

If your MongoDB Server is running locally, you can use the connection string «mongodb://localhost:» where is the port number you configured your server to listen for incoming connections.

If you need to specify a different hostname or IP address, see our Server Manual entry on Connection Strings .

To test whether you can connect to your server, replace the connection string in the Connect to MongoDB Atlas code example and run it.

Compatibility

Due to potential problems representing 64-bit integers on 32-bit platforms, users are advised to use 64-bit environments. When using a 32-bit platform, be aware that any 64-bit integer read from the database will be returned as a MongoDB\BSON\Int64

instance instead of a PHP integer type.

MongoDB Compatibility

The following compatibility table specifies the recommended version(s) of the PHP driver for use with a specific version of MongoDB.

The first column lists the driver version(s).

Источник

Оцените статью