Install the MongoDB PHP Library
The MongoDB PHP Library is a high-level abstraction for the
PHP driver (i.e. mongodb
extension). This page
will briefly explain how to install both the mongodb
extension and the
MongoDB PHP Library.
Installing the Extension
Linux, Unix, and macOS users can either install the extension with PECL (recommended) or manually compile from source. The following command may be used to install the extension with PECL:
Note
If the build process for either installation method fails to find a TLS
library, check that the development packages (e.g. libssl-dev
) and
pkg-config are both installed.
Once the extension is installed, add the following line to your php.ini
file:
Windows users can download precompiled binaries of the extension from
PECL. After extracting the
php_mongodb.dll
file to PHP’s extension directory, add the following line to
your php.ini
file:
Windows binaries are available for various combinations of PHP version, thread-safety, and architecture. Failure to select the correct binary will result in an error attempting to load the extension DLL at runtime. Additional considerations for Windows are discussed in the Windows installation documentation.
Note
If your system has multiple versions of PHP installed, each version will have
its own pecl
command and php.ini
file. Additionally, PHP may also use
separate php.ini
files for its web and CLI environments. If the extension
has been installed but is not available at runtime, double-check that you
have used the correct pecl
command (or binary in the case of Windows) and
have modified the appropriate php.ini
file(s).
Installing the Library
The preferred method of installing the MongoDB PHP Library is with Composer by running the following command from your project root:
While not recommended, you may also manually install the library using a source archive attached to the GitHub releases.
Configure Autoloading
Once you have installed the library, ensure that your application includes Composer’s autoloader as in the following example:
Refer to Composer’s autoloading documentation for more information about setting up autoloading.
If you installed the library manually from a source archive, you will need to manually configure autoloading:
- Map the top-level
MongoDB\
namespace to thesrc/
directory using your preferred autoloader implementation. - Manually require the
src/functions.php
file. This is necessary because PHP does not support autoloading for functions.