MongoDB PHP Driver

The PHP driver consists of two components, the MongoDB extension and library.

The extension provides a low-level API and mainly serves to integrate libmongoc and libbson with PHP.

While it is possible to use the extension alone, users are strongly encouraged to use the extension and library together. The library provides a high-level API consistent with other MongoDB language drivers.

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 on the command line:

$ sudo pecl install mongodb

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

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

Additional installation instructions may be found in the library documentation.

To connect to a MongoDB Atlas cluster, use the Atlas connection string for your cluster:

$client = new MongoDB\Client(
$db = $client->test;

To connect to a database running locally on its default port, change the connection string to "mongodb://localhost".

To connect to a database running locally, change the connection string to "mongodb://localhost:<port>".

Your mongod instance must be running to successfully connect to your database. For information on how to start your mongod instance, see the Manage mongod Processes Server Manual Entry.

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.

PHP Driver Versions
MongoDB 4.4
MongoDB 4.2
MongoDB 4.0
MongoDB 3.6
MongoDB 3.4
MongoDB 3.2
MongoDB 3.0
MongoDB 2.6
ext 1.9 + lib 1.8
ext 1.8 + lib 1.7
ext 1.7 + lib 1.6
ext 1.6 + lib 1.5
ext 1.5 + lib 1.4
ext 1.4 + lib 1.3
ext 1.3 + lib 1.2
ext 1.2 + lib 1.1
ext 1.1 + lib 1.0
ext 1.0
PHP Driver Versions
PHP 8.0
PHP 7.4
PHP 7.3
PHP 7.2
PHP 7.1
PHP 7.0
PHP 5.6
PHP 5.5
ext 1.9 + lib 1.8
ext 1.8 + lib 1.7
ext 1.7 + lib 1.6
ext 1.6 + lib 1.5
ext 1.5 + lib 1.4
ext 1.4 + lib 1.3
ext 1.3 + lib 1.2

For more information on how to read the compatibility tables, see our guide on MongoDB Compatibility Tables.

Give Feedback

On this page

  • Introduction
  • Installation
  • Connect to MongoDB Atlas
  • Connect to localhost
  • Compatibility
  • See Also