Skip to content

MongoDB with the PHP library

Uses mongodb/mongodb 2.5 and the mongodb extension 2.5. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

mongodb://app:secret@mongo.example.com:27017/shop?authSource=admin
mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin

The address comes from the environment variable MONGODB_URI, so switching to MachNoSQL changes configuration only.

Terminal window
export MONGODB_URI='mongodb://app:secret@machnosql.example.com:27017/shop?authSource=admin'
pecl install mongodb
composer install
php app.php

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

app.php
<?php
// Orders example for MongoDB, unchanged on MachNoSQL.
require __DIR__ . '/vendor/autoload.php';
$client = new MongoDB\Client(getenv('MONGODB_URI'));
$orders = $client->selectCollection('shop', 'orders');
$orders->deleteMany([]);
$orders->insertMany([
['customer' => 'ada', 'item' => 'keyboard', 'qty' => 1, 'price' => 49.0],
['customer' => 'ada', 'item' => 'mouse', 'qty' => 2, 'price' => 19.5],
['customer' => 'linus', 'item' => 'monitor', 'qty' => 1, 'price' => 199.0],
]);
var_dump($orders->findOne(['item' => 'mouse']));
$orders->updateOne(['item' => 'mouse'], ['$inc' => ['qty' => 1]]);
$rows = $orders->aggregate([
['$group' => ['_id' => '$customer', 'revenue' => ['$sum' => ['$multiply' => ['$qty', '$price']]]]],
['$sort' => ['revenue' => -1]],
]);
foreach ($rows as $row) {
echo json_encode($row), PHP_EOL;
}
composer.json
{
"name": "example/machnosql-mongodb",
"require": {
"php": ">=8.3",
"ext-mongodb": "^2.5",
"mongodb/mongodb": "^2.5"
}
}