MongoDB and PHP on Raspberry OS

Install MongoDB drivers

Install PECL

sudo apt install php-pear phpX.X-dev # X.X is PHP verion used
sudo pecl install mongodb
# the system could require to update PECL
# sudo pecl channel-update pecl.php.net

Create an .ini module (check what PHP version is installed)

sudo nano /etc/php/8.0/mods-available/mongodb.ini

Add the following line:

extension=mongodb.so

Save, enable module, and restart the Apache server:

sudo phpenmod mongodb
sudo service apache2 resstart

MongoDB PHP Library

The preferred method of installing this library is with Composer by running the following from your project root:

composer require mongodb/mongodb

It’s time to test…

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

$collection = (new MongoDB\Client)->test->users;
$insertOneResult = $collection->insertOne([
    'username' => 'admin',
    'email' => 'admin@example.com',
    'name' => 'Admin User',
]);

printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());

Additional resources:
https://www.w3schools.com/mongodb/mongodb_drivers.php
https://www.w3schools.com/mongodb/index.php

Leave a Reply

Your email address will not be published.

Yandex.Metrica