PHPackages                             zealphp/mongodb - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. zealphp/mongodb

ActiveLibrary[Database &amp; ORM](/categories/database)

zealphp/mongodb
===============

Async MongoDB driver for ZealPHP — Rust extension with PHP OOP library, non-blocking via eventfd + OpenSwoole coroutines

v0.2.15(2w ago)50MITPHPPHP &gt;=8.1CI passing

Since May 19Pushed 2w ago1 watchersCompare

[ Source](https://github.com/sibidharan/zealphp-mongodb)[ Packagist](https://packagist.org/packages/zealphp/mongodb)[ Docs](https://github.com/sibidharan/zealphp-mongodb)[ RSS](/packages/zealphp-mongodb/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (6)Versions (17)Used By (0)

zealphp-mongodb
===============

[](#zealphp-mongodb)

[![Tests](https://github.com/sibidharan/zealphp-mongodb/actions/workflows/tests.yml/badge.svg)](https://github.com/sibidharan/zealphp-mongodb/actions/workflows/tests.yml)[![Coding Standards](https://github.com/sibidharan/zealphp-mongodb/actions/workflows/coding-standards.yml/badge.svg)](https://github.com/sibidharan/zealphp-mongodb/actions/workflows/coding-standards.yml)[![Static Analysis](https://github.com/sibidharan/zealphp-mongodb/actions/workflows/static-analysis.yml/badge.svg)](https://github.com/sibidharan/zealphp-mongodb/actions/workflows/static-analysis.yml)[![Coverage](https://camo.githubusercontent.com/fe5c7e352b78254d38aeafcd25e0286a9a3385d27f38f1b5de145a181eaa63f7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d39342532352d627269676874677265656e)](https://github.com/sibidharan/zealphp-mongodb)

Async MongoDB driver for PHP — a Rust extension bridging the official [mongo-rust-driver](https://github.com/mongodb/mongo-rust-driver) into PHP via [ext-php-rs](https://github.com/davidcole1340/ext-php-rs), with non-blocking coroutine support through [OpenSwoole](https://openswoole.com/).

Drop-in replacement for [`mongodb/mongodb`](https://github.com/mongodb/mongo-php-library) with the same Collection, Database, Client, and BSON APIs.

Performance
-----------

[](#performance)

**C driver parity achieved.** 7 of 10 operations match or beat the official C driver (`ext-mongodb`). Total overhead: +4.1%.

200 iterations, median timing, PHP 8.4.5, MongoDB 6.0, same host:

Operationzealphp-mongodbext-mongodb (C)GapfindOne0.442ms0.451ms**-1.9%**find(50)0.550ms0.494ms+11.3%find(1000)4.270ms3.764ms+13.4%insertOne0.297ms0.292ms+1.6%updateOne0.493ms0.519ms**-5.0%**deleteOne0.598ms0.610ms**-2.1%**countDocuments0.883ms0.901ms**-2.1%**aggregate1.415ms1.458ms**-2.9%**distinct0.795ms0.820ms**-3.0%**findOneAndUpdate0.511ms0.539ms**-5.1%**With coroutine parallelism (ZealPHP/OpenSwoole), 4 parallel queries complete in **0.69ms** vs 1.7ms sequential on the C driver — **3.4x faster**. Under HTTP concurrency (`ab -n 500 -c 20`), throughput is **3.9x–6.7x higher** than Apache + C driver:

EndpointApache (C driver)ZealPHP (Rust driver)SpeedupLanding page (5 DB queries)120 req/s · 78ms p50465 req/s · 20ms p50**3.9x**/features (lightweight)254 req/s · 37ms p501699 req/s · 5ms p50**6.7x**Measured in production on the same container, same MongoDB, same dataset (10k+ users). The landing page parallelizes 5 count queries via `Channel(5)` + `go()` coroutines; Apache runs them sequentially.

See [docs/case-study-dual-runtime.md](docs/case-study-dual-runtime.md) for the full analysis.

Features
--------

[](#features)

- **Full API parity** with the official PHP MongoDB library — Collection (25 methods), Database (15 methods), Client (12 methods)
- **Non-blocking async** via eventfd + OpenSwoole `Event::add` + `Channel` — zero thread blocking in coroutine mode
- **Complete BSON type system** — ObjectId, UTCDateTime, Regex, Binary, Decimal128, Int64, Timestamp, Javascript, MinKey, MaxKey, Document, PackedArray
- **All query options** — upsert, returnDocument, projection, sort, limit, skip on both sync and async paths
- **Rust performance** — backed by the official MongoDB Rust driver with tokio async runtime
- **Connection pooling** — persistent connections across requests, managed by the Rust extension
- **Dual-mode operation** — sync (block\_on) without OpenSwoole, async (eventfd) with OpenSwoole coroutines

Requirements
------------

[](#requirements)

- PHP &gt;= 8.1
- Rust toolchain (for building the extension)
- MongoDB server 5.0+
- OpenSwoole (optional, for async coroutine mode)

Installation
------------

[](#installation)

### Build the Rust extension

[](#build-the-rust-extension)

```
# 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
```

### Docker

[](#docker)

The extension builds automatically in Docker — see the [labs-devops Dockerfile](https://github.com/sibidharan/labs-devops) for reference:

```
COPY --from=rust:latest /usr/local/cargo /usr/local/cargo
COPY --from=rust:latest /usr/local/rustup /usr/local/rustup
ENV PATH="/usr/local/cargo/bin:${PATH}"

RUN apt-get install -y libclang-dev && \
    git clone https://github.com/sibidharan/zealphp-mongodb.git /tmp/zealphp-mongodb && \
    cd /tmp/zealphp-mongodb/ext && cargo build --release && \
    cp target/release/libzealphp_mongodb.so $(php -r "echo ini_get('extension_dir');")/zealphp_mongodb.so && \
    rm -rf /tmp/zealphp-mongodb/ext/target
```

### Install the PHP library

[](#install-the-php-library)

```
composer require zealphp/mongodb
```

Quick Start
-----------

[](#quick-start)

```
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' => 'bob@example.com'],
    ['$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'),
]);
```

Async Mode (OpenSwoole)
-----------------------

[](#async-mode-openswoole)

When running inside an OpenSwoole coroutine, all MongoDB operations automatically become non-blocking:

```
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";
    }
});
```

API Reference
-------------

[](#api-reference)

### Collection Methods

[](#collection-methods)

MethodDescription`findOne($filter, $options)`Find a single document`find($filter, $options)`Find documents (returns Cursor)`insertOne($document)`Insert a single document`insertMany($documents)`Insert multiple documents`updateOne($filter, $update, $options)`Update a single document`updateMany($filter, $update, $options)`Update multiple documents`deleteOne($filter)`Delete a single document`deleteMany($filter)`Delete multiple documents`replaceOne($filter, $replacement, $options)`Replace a single document`countDocuments($filter)`Count documents matching filter`estimatedDocumentCount()`Fast approximate count`distinct($field, $filter)`Get distinct values`aggregate($pipeline)`Run aggregation pipeline`findOneAndUpdate($filter, $update, $options)`Find and update atomically`findOneAndDelete($filter)`Find and delete atomically`findOneAndReplace($filter, $replacement, $options)`Find and replace atomically`bulkWrite($operations)`Execute bulk operations`createIndex($keys, $options)`Create an index`createIndexes($indexes)`Create multiple indexes`listIndexes()`List collection indexes`dropIndex($name)`Drop an index`dropIndexes()`Drop all indexes`drop()`Drop the collection`rename($newName)`Rename the collection`count($filter)`Alias for countDocuments### Database Methods

[](#database-methods)

MethodDescription`command($command)`Run a database command`aggregate($pipeline)`Database-level aggregation`createCollection($name)`Create a collection`dropCollection($name)`Drop a collection`drop()`Drop the database`listCollections()`List collections`listCollectionNames()`List collection names`selectCollection($name)`Get a Collection instance`selectGridFSBucket()`Get a GridFS Bucket (stub)### BSON Types

[](#bson-types)

TypeExtended JSON`ObjectId``{"$oid": "..."}``UTCDateTime``{"$date": {"$numberLong": "..."}}``Regex``{"$regularExpression": {"pattern": "...", "options": "..."}}``Binary``{"$binary": {"base64": "...", "subType": "..."}}``Decimal128``{"$numberDecimal": "..."}``Int64`Native int`Timestamp``{"$timestamp": {"t": ..., "i": ...}}``Javascript``{"$code": "..."}``MinKey``{"$minKey": 1}``MaxKey``{"$maxKey": 1}`Architecture
------------

[](#architecture)

```
┌─────────────────────────────────────────────────┐
│                  PHP Application                │
│  Collection / Database / Client / BSON types    │
├─────────────────────────────────────────────────┤
│              AsyncBridge (PHP)                  │
│  isCoroutineMode() → eventfd path or sync path  │
├──────────────────────┬──────────────────────────┤
│   Sync Path          │     Async Path           │
│   block_on(future)   │  spawn_task → eventfd    │
│                      │  Event::add → Channel    │
├──────────────────────┴──────────────────────────┤
│           Rust Extension (ext-php-rs)           │
│  34 PHP functions · BSON conversion · Pool      │
├─────────────────────────────────────────────────┤
│        mongo-rust-driver + tokio runtime        │
│          Connection pooling · TLS · Auth        │
├─────────────────────────────────────────────────┤
│              MongoDB Server                     │
└─────────────────────────────────────────────────┘

```

Development
-----------

[](#development)

```
# Install dev dependencies
composer install

# Run unit tests (no MongoDB needed)
vendor/bin/phpunit --testsuite Unit

# Run integration tests (requires MongoDB + ext)
MONGODB_URI=mongodb://localhost:27017 vendor/bin/phpunit --testsuite Integration

# Check coding standards
vendor/bin/phpcs

# Auto-fix coding standards
vendor/bin/phpcbf

# Static analysis
vendor/bin/psalm

# PHP modernization check
vendor/bin/rector --dry-run
```

License
-------

[](#license)

MIT

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance97

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

16

Last Release

15d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/10979210?v=4)[Sibidharan](/maintainers/sibidharan)[@sibidharan](https://github.com/sibidharan)

---

Top Contributors

[![sibidharan](https://avatars.githubusercontent.com/u/10979210?v=4)](https://github.com/sibidharan "sibidharan (84 commits)")

---

Tags

asyncmongodbcoroutinerustopenswoolezealphpeventfd

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm, Rector

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/zealphp-mongodb/health.svg)

```
[![Health](https://phpackages.com/badges/zealphp-mongodb/health.svg)](https://phpackages.com/packages/zealphp-mongodb)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k8.0M84](/packages/mongodb-laravel-mongodb)[doctrine/mongodb-odm

PHP Doctrine MongoDB Object Document Mapper (ODM) provides transparent persistence for PHP objects to MongoDB.

1.1k24.1M343](/packages/doctrine-mongodb-odm)[alcaeus/mongo-php-adapter

Adapter to provide ext-mongo interface on top of mongo-php-library

47112.5M74](/packages/alcaeus-mongo-php-adapter)[leroy-merlin-br/mongolid

Easy, powerful and ultrafast ODM for PHP and MongoDB.

11235.2k6](/packages/leroy-merlin-br-mongolid)[moloquent/moloquent

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)

120115.3k7](/packages/moloquent-moloquent)[doesntmattr/mongodb-migrations

Managed Database Migrations for MongoDB

23608.7k1](/packages/doesntmattr-mongodb-migrations)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
