MongoDB - PHP Driver
This section is about using MongoDB in PHP.
First, you have to install the PHP extension.
Linux
You may follow this tutorial or the documentation.
$ sudo apt-get update
$ sudo apt-get install php-dev php-pear
$ sudo pecl install mongodb # add -version if needed
$ # sudo pecl uninstall mongodb # if needed
On Debian, do not edit php.ini
.
$ sudo nano /etc/php/x.x/mods-available/mongodb.ini
extension=mongodb.so
$ sudo phpenmod mongodb
$ sudo systemctl restart apache2 # Apache
To test π»: sudo apt install php7.4-mongodb
.
Windows
You may follow this tutorial.
First, you have to find out if your web server is thread-safe (TS) or not. Use phpinfo()
and search for Thread Safety
.
# 1.13.0 == MongDB version
# 7.4 == PHP version
# ts == thread-safe, nts == not thread-safe
$ wget https://windows.php.net/downloads/pecl/releases/mongodb/1.13.0/php_mongodb-1.13.0-7.4-ts-vc15-x64.zip
$ unzip php_mongodb-1.13.0-7.4-ts-vc15-x64.zip
$ mv "php_mongodb.dll" "C:\wamp64\bin\php\ext\"
Edit php.ini
and add extension=mongodb.dll
or extension=mongodb
. Restart your server.
You should see mongodb in the extension list shown by phpinfo()
.
Then, you install it using composer:
$ composer require mongodb/mongodb
A simple starter script with no framework:
<?php
require 'vendor/autoload.php'; // composer autoloader
$client = new MongoDB\Client('mongodb://xxx');
// or
$client = new MongoDB\Client('mongodb://xxx', [
'username' => "",
'password' => ""
]);
Refer to the documentation.
Examples
Get a database
$db = $client->db_name;
$db = $client->{'db_name'};
Get a collection
$collection = $db->collection_name;
$collection = $db->{'collection_name'};
Update a document
$result = $collection->updateOne(
[ 'attribute' => "value" ],
[
'$set' => [ 'attribute' => "new_value"],
'$unset' => ['attribute2' => true],
]
);
$r = $result->getModifiedCount();
$r = $result->getMatchedCount();
Find documents
$result = $collection->find(...)->toArray()
foreach ($result as $r){
// ...
}
$result = $collection->findOne(...);
if ($result === null) {
// not found
}
Some examples of values for parameters:
$filter = [ 'name' => "..." ];
$filter = [ 'name' => ['$exists' => true] ];
$projection =
[
'projection' => [
'name' => true,
'age' => true,
'email' => true
]
]
;