PHP code example of zealphp / mongodb

1. Go to this page and download the library: Download zealphp/mongodb library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

zealphp / mongodb example snippets


use ZealPHP\MongoDB\Client;

$client = new Client('mongodb://localhost:27017');
$db = $client->selectDatabase('myapp');
$users = $db->selectCollection('users');

// Insert
$result = $users->insertOne(['name' => 'Alice', 'age' => 30]);
echo $result->getInsertedId();

// Find
$user = $users->findOne(['name' => 'Alice']);
echo $user->name; // Property access (Document extends ArrayObject)
echo $user['age']; // Array access also works

// Find with options
$cursor = $users->find(
    ['age' => ['$gt' => 18]],
    ['sort' => ['age' => -1], 'limit' => 10, 'projection' => ['name' => 1]]
);
foreach ($cursor as $doc) {
    echo $doc->name . "\n";
}

// Update with upsert
$users->updateOne(
    ['email' => '[email protected]'],
    ['$set' => ['name' => 'Bob', 'age' => 25]],
    ['upsert' => true]
);

// Aggregate
$pipeline = [
    ['$group' => ['_id' => '$department', 'avg_age' => ['$avg' => '$age']]],
    ['$sort' => ['avg_age' => -1]],
];
foreach ($users->aggregate($pipeline) as $doc) {
    echo "{$doc->_id}: {$doc->avg_age}\n";
}

// BSON types
use ZealPHP\MongoDB\BSON\ObjectId;
use ZealPHP\MongoDB\BSON\UTCDateTime;
use ZealPHP\MongoDB\BSON\Regex;

$users->insertOne([
    '_id' => new ObjectId(),
    'created_at' => new UTCDateTime(),
    'username' => new Regex('^admin', 'i'),
]);

use OpenSwoole\Runtime;
use OpenSwoole\Coroutine;
use ZealPHP\MongoDB\Client;

Runtime::enableCoroutine(OPENSWOOLE_HOOK_ALL);

// Connect BEFORE coroutine context (pool::connect uses block_on)
$client = new Client('mongodb://localhost:27017');

Coroutine::run(function() use ($client) {
    $db = $client->selectDatabase('myapp');
    $col = $db->users;

    // This yields the coroutine via eventfd — other coroutines run while waiting
    $user = $col->findOne(['name' => 'Alice']);

    // Concurrent MongoDB operations
    $chan = new Coroutine\Channel(3);
    for ($i = 0; $i < 3; $i++) {
        Coroutine::create(function() use ($col, $i, $chan) {
            $count = $col->countDocuments(['department' => "dept_$i"]);
            $chan->push("dept_$i: $count");
        });
    }
    for ($i = 0; $i < 3; $i++) {
        echo $chan->pop() . "\n";
    }
});
bash
# Prerequisites
sudo apt-get install -y php-dev libclang-dev   # PHP headers + libclang for bindgen
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh  # Rust 1.88+

# Build
cd ext
cargo build --release

# Install
sudo cp target/release/libzealphp_mongodb.so $(php -r "echo ini_get('extension_dir');")/zealphp_mongodb.so
echo "extension=zealphp_mongodb.so" | sudo tee $(php --ini | grep "Scan for" | cut -d: -f2 | tr -d ' ')/99-zealphp-mongodb.ini

# Verify
php -r "echo zealphp_mongodb_version();"  # should print 0.2.5