PHPackages                             xp-forge/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. xp-forge/mongodb

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

xp-forge/mongodb
================

MongoDB connectivity for XP Framework

v3.7.0(7mo ago)022.7k—3%[2 issues](https://github.com/xp-forge/mongodb/issues)1BSD-3-ClausePHPPHP &gt;=7.4.0CI passing

Since Aug 4Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/xp-forge/mongodb)[ Packagist](https://packagist.org/packages/xp-forge/mongodb)[ Docs](http://xp-framework.net/)[ RSS](/packages/xp-forge-mongodb/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (58)Used By (1)

MongoDB connectivity
====================

[](#mongodb-connectivity)

[![Build status on GitHub](https://github.com/xp-forge/mongodb/workflows/Tests/badge.svg)](https://github.com/xp-forge/mongodb/actions)[![XP Framework Module](https://raw.githubusercontent.com/xp-framework/web/master/static/xp-framework-badge.png)](https://github.com/xp-framework/core)[![BSD Licence](https://raw.githubusercontent.com/xp-framework/web/master/static/licence-bsd.png)](https://github.com/xp-framework/core/blob/master/LICENCE.md)[![Requires PHP 7.4+](https://raw.githubusercontent.com/xp-framework/web/master/static/php-7_4plus.svg)](http://php.net/)[![Supports PHP 8.0+](https://raw.githubusercontent.com/xp-framework/web/master/static/php-8_0plus.svg)](http://php.net/)[![Latest Stable Version](https://camo.githubusercontent.com/1e3ca44e11a12e3c637921718660c96cbc7b96560e7b5c06b777e56a9a404df3/68747470733a2f2f706f7365722e707567782e6f72672f78702d666f7267652f6d6f6e676f64622f76657273696f6e2e737667)](https://packagist.org/packages/xp-forge/mongodb)

This library implements MongoDB connectivity via its binary protocol. It has no dependencies on the PHP extension.

- ✅ Local MongoDB installations
- ✅ [MongoDB Atlas](https://www.mongodb.com/docs/atlas/) and [Atlas Search](https://www.mongodb.com/docs/atlas/atlas-search/)
- ✅ [Azure Cosmos DB for MongoDB](https://learn.microsoft.com/en-us/azure/cosmos-db/mongodb/introduction)

Examples
--------

[](#examples)

Finding documents inside a collection:

```
use com\mongodb\{MongoConnection, ObjectId};
use util\cmd\Console;

$c= new MongoConnection('mongodb://localhost');
$id= new ObjectId('...');

// Find all documents
$cursor= $c->collection('test.products')->query();

// Find document with the specified ID
$cursor= $c->collection('test.products')->query($id);

// Find all documents with a name of "Test"
$cursor= $c->collection('test.products')->query(['name' => 'Test']);

// Use aggregation pipelines
$cursor= $c->collection('test.products')->query([
  ['$match' => ['color' => 'green', 'state' => 'ACTIVE']],
  ['$lookup' => [
    'from'         => 'users',
    'localField'   => 'owner.id',
    'foreignField' => '_id',
    'as'           => 'owner',
  ]],
  ['$addFields' => ['owner' => ['$first' => '$owner']]],
]);

foreach ($cursor as $document) {
  Console::writeLine('>> ', $document);
}
```

Inserting a document into a collection:

```
use com\mongodb\{MongoConnection, Document};
use util\cmd\Console;

$c= new MongoConnection('mongodb://localhost');

$result= $c->collection('test.products')->insert(new Document([
  'name' => 'Test',
  'qty'  => 10,
  'tags' => ['new', 'tested'],
]));
Console::writeLine('>> ', $result);
```

Updating documents:

```
use com\mongodb\{MongoConnection, ObjectId};
use util\cmd\Console;

$c= new MongoConnection('mongodb://localhost');
$id= new ObjectId('...');

// Select a single document for updating by its ID
$result= $c->collection('test.products')->update($id, ['$inc' => ['qty' => 1]]);

// Apply to all documents matchig a given filter
$result= $c->collection('test.products')->update(['name' => 'Test'], ['$inc' => ['qty' => 1]]);

Console::writeLine('>> ', $result);

// Return document after modification
$result= $c->collection('test.products')->modify($id, ['$inc' => ['qty' => 1]]);
Console::writeLine('>> ', $result->kind(), ' ', $result->document());
```

[Upserting](https://www.mongodb.com/docs/manual/reference/command/update/#std-label-update-command-upsert) documents:

```
use com\mongodb\{MongoConnection, Document};
use util\cmd\Console;

$c= new MongoConnection('mongodb://localhost');

$result= $c->collection('test.products')->upsert(['slug' => 'test'], new Document([
  'slug' => 'test',
  'name' => 'Test',
  'qty'  => 10,
  'tags' => ['new', 'tested'],
]));

Console::writeLine('>> ', $result);
```

Deleting documents:

```
use com\mongodb\{MongoConnection, ObjectId};
use util\cmd\Console;

$c= new MongoConnection('mongodb://localhost');
$id= new ObjectId('...');

// Select a single document to be removed
$result= $c->collection('test.products')->delete($id);

// Remove all documents matchig a given filter
$result= $c->collection('test.products')->delete(['name' => 'Test']);

Console::writeLine('>> ', $result);

// Return deleted document
$result= $c->collection('test.products')->remove($id);
Console::writeLine('>> ', $result->kind(), ' ', $result->document());
```

*Note: All of the above have used the `collection()` shortcut which is equivalent to chaining `database('test')->collection('products')`.*

Authentication
--------------

[](#authentication)

To authenticate, pass username and password via the connection string, e.g. `mongodb://user:pass@localhost`. The authentication source defaults to *admin* but can be set by supplying a path, e.g. `mongodb://user:pass@localhost/test`.

Both *SCRAM-SHA-256* and *SCRAM-SHA-1* are supported as authentication mechanisms. Which one is used is negotiated upon connecting with the server / cluster. To explicitely select the authentication mechanism, pass it as part of the connection string, e.g. `mongodb://user:pass@localhost?authMechanism=SCRAM-SHA-256`.

SSL / TLS
---------

[](#ssl--tls)

To connect via SSL / TLS, pass `ssl=true` as connection string parameters, e.g.:

```
use com\mongodb\MongoConnection;

$c= new MongoConnection('mongodb://localhost?ssl=true');

// Explicit call to connect, can be omitted when using collection()
$c->connect();
```

Aggregation
-----------

[](#aggregation)

The `Collection` class also features aggregation methods:

- `count($filter= [])`
- `distinct($key, $filter= [])`
- `aggregate($pipeline)`

See

Commands
--------

[](#commands)

To run commands on a given collection, use the *run()* method:

```
use com\mongodb\MongoConnection;

$c= new MongoConnection('mongodb+srv://server.example.com');

// A simple connection-wide command without arguments
$result= $c->run('ping')->value();

// A command might return a cursor
$indexes= $c->collection('app.sessions')->run('listIndexes', [], 'read');
foreach ($indexes->cursor() as $index) {
  // ...
}
```

See  for a list of commands.

DNS Seed List Connection
------------------------

[](#dns-seed-list-connection)

Adding in DNS to specify clusters adds another level of flexibility to deployment. Given the following DNS entries:

```
Record                            TTL   Class    Priority Weight Port  Target
_mongodb._tcp.server.example.com. 86400 IN SRV   0        5      27317 mongodb1.example.com.
_mongodb._tcp.server.example.com. 86400 IN SRV   0        5      27017 mongodb2.example.com.

```

...the following code will connect to one of the above:

```
use com\mongodb\MongoConnection;

$c= new MongoConnection('mongodb+srv://server.example.com');
$c->connect();
```

Sessions
--------

[](#sessions)

Using a causally consistent session, an application can read its own writes and is guaranteed monotonic reads, even when reading from replica set secondaries.

```
use com\mongodb\{MongoConnection, ObjectId};
use util\cmd\Console;

$c= new MongoConnection('mongodb+srv://server.example.com?readPreference=secondary');
$session= $c->session();

$id= new ObjectId('...');

// Will write to primary
$collection= $c->collection('test.products');
$collection->update($id, ['$set' => ['qty' => 1]], $session);

// Will read the updated document
$updated= $collection->find($id, $session);

$session->close();
```

Handling errors
---------------

[](#handling-errors)

All operations raise instances of the `com.mongodb.Error` class. Connection and authentication errors can be handled by checking for *CannotConnect*:

```
use com\mongodb\{MongoConnection, Error, CannotConnect};
use util\cmd\Console;

$c= new MongoConnection('mongodb+srv://user:pass@mongo.example.com');
try {
  $c->connect();
} catch (CannotConnect $e) {
  // Error during authentication phase, e.g.:
  // - DNS errors
  // - None of the replica set members is reachable
  // - Authentication failed
} catch (Error $e) {
  // Any other error
}
```

Type mapping
------------

[](#type-mapping)

All builtin types are mapped to their BSON equivalents. In addition, the following type mappings are used:

- `util.Date` =&gt; UTC datetime
- `util.Bytes` =&gt; Binary data
- `util.UUID` =&gt; UUID binary data
- `com.mongodb.Int64` =&gt; 64-bit integer
- `com.mongodb.Decimal128` =&gt; 128-bit decimal
- `com.mongodb.ObjectId` =&gt; Object ID
- `com.mongodb.Timestamp` =&gt; Timestamp
- `com.mongodb.Regex` =&gt; Regular expression
- `com.mongodb.Encrypted` =&gt; Encrypted values

The deprecated types of the BSON spec are not supported, see

###  Health Score

45

—

FairBetter than 93% of packages

Maintenance63

Regular maintenance activity

Popularity25

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity68

Established project with proven stability

 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 ~35 days

Recently: every ~17 days

Total

55

Last Release

227d ago

Major Versions

v0.11.0 → v1.0.02022-03-25

v1.15.0 → v2.0.02023-08-19

v2.5.1 → v3.0.02025-01-25

PHP version history (2 changes)v0.1.0PHP &gt;=7.0.0

v3.0.0PHP &gt;=7.4.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/07d18d882c8b4aaf3466432f64018214f2771eda333202175431ee7233795376?d=identicon)[thekid](/maintainers/thekid)

---

Top Contributors

[![thekid](https://avatars.githubusercontent.com/u/696742?v=4)](https://github.com/thekid "thekid (463 commits)")

---

Tags

bsoncompressioncosmosdbmongodbmongodb-atlasmongodb-drivermongodb-phpprotocolreplica-setscram-sha-1scram-sha-256sessionssnappytransactionsxp-frameworkzlibzstandardmodulexp

### Embed Badge

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

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

PHPackages © 2026

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