Install MongoDB PHP8 Library On Ubuntu 20.08
Adam C. |

PHP's naming convention is horribly inconsistent! So in order to make commands listed below work for you, please make sure:

  1. Your OS is Ubuntu 20.08
  2. Your PHP version is 8.0
Photo by Ben Griffiths on Unsplash

Let's start with the error:

PHP Fatal error:  Uncaught Error: Class "MongoDB\Driver\Manager" not found in /var/www/dnx-mailer/vendor/mongodb/mongodb/src/Client.php:130
Stack trace:
#0 /var/www/dnx-mailer/sendInvitation.php(10): MongoDB\Client->__construct()
#1 {main}
  thrown in /var/www/dnx-mailer/vendor/mongodb/mongodb/src/Client.php on line 130

It's easy to know:

  1. You're using composer
  2. Unfortunately, composer require mongodb/mongodb does not install mongodb extension for you. So you would need to do this by your own.

Not sure there is another way, I hope it can be installed by apt-get , like apt-get install php-mongodb, or php8.0-mongodb (you know what I mean -  PHP's naming convention is horrible!) If you want to save some time, let's just do this thru PECL  (warning - their website is very old school, like 1998.) How to install PECL?

Here you go: (again, you may think it would be php8.0-pear, but it's not.)

apt-get install php-pear 

Okay can I run pecl install mongodb now? Sorry! not yet, otherwise, you will see this error:

Warning: foreach() argument must be of type array|object, null given in Command.php on line 249

Someone said, that's because php-xml is missing, so install the following, likely on php8.0-xml is needed, but install them anyway, and yes, we need specify php8.0-xxx:

apt-get install php8.0-fpm libapache2-mod-php8.0 php8.0-mysql php8.0-xml

Are we good now? Not, still not. There is another error:

running: phpize
sh: 1: phpize: not found
ERROR: `phpize' failed

We need php-dev, 

apt-get install php8.0-dev // or php-dev works too, not sure if they are the same

Finally, run 

pecl install mongodb

The last step is adding it to the php.ini, since I only use it for CLI, I add “extension=mongodb.so” to “/etc/php/8.0/cli/php.ini”.

Hope this helps.

Updated 09/19/2022

Just setup another LAMP server, at this time, I am using PHP8.1, the process above is still valid, but just remember to change “8.0” to “8.1”. Here are additional notes:

  1. you don't need to install both php8.1-fpm and libapache2-mod-php8.1, fpm (FastCGI Process Manager) is for Nginx, so if you are using Apache, then it's unnecessary. (could be a 
  2. Since my project needs curl, I installed php8.1-curl. After installation, it tells me to run  a2enconf php8.1-fpm. I did, but it was a disaster.  Because I am using Apache, after enabling fpm, the MongoDB driver for PHP failed to load. I tried to reinstall everything, and then figured out I could just disable fpm by a2disconf php8.1-fpm