PHPackages                             witer/codeigniter-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. witer/codeigniter-mongodb

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

witer/codeigniter-mongodb
=========================

Native Codeigniter 4 DB driver for MongoDB

25PHP

Since Oct 8Pushed 8mo agoCompare

[ Source](https://github.com/WitER/codeigniter-mongodb)[ Packagist](https://packagist.org/packages/witer/codeigniter-mongodb)[ RSS](/packages/witer-codeigniter-mongodb/feed)WikiDiscussions main Synced today

READMEChangelogDependenciesVersions (2)Used By (0)

CodeIgniter 4 MongoDB Driver
============================

[](#codeigniter-4-mongodb-driver)

[![Build & Tests](https://github.com/WitER/codeigniter-mongodb/actions/workflows/php.yml/badge.svg)](https://github.com/WitER/codeigniter-mongodb/actions/workflows/php.yml)[![Packagist Version](https://camo.githubusercontent.com/9881503d711d7ffdf5d31ec082676cc0b14827cf7adb41cfa6cf8fb26eea1c02/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f77697465722f636f646569676e697465722d6d6f6e676f64622e737667)](https://packagist.org/packages/witer/codeigniter-mongodb)[![PHP Version](https://camo.githubusercontent.com/806829349c4c35dcd3f556a363d7d2b5958fbd0b9cb85fd10db18a8729e41aef/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f77697465722f636f646569676e697465722d6d6f6e676f64622e737667)](https://packagist.org/packages/witer/codeigniter-mongodb)[![Downloads](https://camo.githubusercontent.com/3cfe70e34f01a158d611ee6dfdd15f08e7ab15ff75d1b94b63842605716325a7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f77697465722f636f646569676e697465722d6d6f6e676f64622e737667)](https://packagist.org/packages/witer/codeigniter-mongodb)[![GitHub issues](https://camo.githubusercontent.com/706d28bbf0296082fb14db31edf647bc47f4f289100566563bfd885fb9c19d77/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f57697445522f636f646569676e697465722d6d6f6e676f64622e737667)](https://github.com/WitER/codeigniter-mongodb/issues)[![GitHub stars](https://camo.githubusercontent.com/9c25320907dd18d0e0577a4dfde1322686cc0f8c6dbc6c593482a213b172bc7b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f57697445522f636f646569676e697465722d6d6f6e676f64622e7376673f7374796c653d736f6369616c)](https://github.com/WitER/codeigniter-mongodb)

> **Disclaimer:** This driver doesn't claim to have high code quality and functionality. If you need it or have ideas/desire/time to improve it, it would be great.

Native MongoDB database driver for CodeIgniter 4. Fully integrates with CI4's connection factory (Config\\Database::connect()) and the Query Builder. It provides a convenient API for MongoDB CRUD operations, aggregations, and transactions while keeping familiar CodeIgniter interfaces.

Features
--------

[](#features)

- Connect to MongoDB through the standard CodeIgniter DB interface (`DBDriver => 'MongoDB'`).
- Most Query Builder methods supported: `select`, `where`/`orWhere`, `whereIn`, `like`, `orderBy`, `limit`/`offset`, `insert`/`update`/`delete`, `insertBatch`/`updateBatch`/`replace`, and more.
- Mongo-specific builder operations: `setInc`/`setDec` ($inc), `unsetField` ($unset), `setOnInsert` ($setOnInsert), `push`/`pull`/`addToSet` (array operations), upsert flag, allow writes without a filter. (**NOT TESTED**)
- Aggregations: `select[Min|Max|Avg|Sum|Count]` and pipeline building for aggregate().
- MongoDB transactions via driver sessions (**replica set required**).
- getCompiled… helpers for debugging: output of "pseudo-SQL"/Mongo JSON request.
- Compatible with CodeIgniter 4 Models/Entities (including field casting).
- Introspection methods: list collections, fields, index info, read validator schema.

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

[](#requirements)

- PHP &gt;= 8.1
- ext-mongodb
- mongodb/mongodb
- CodeIgniter 4 (develop branch is used for tests in this repo)

See composer.json for exact versions.

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

[](#installation)

Via Composer:

```
composer require witer/codeigniter-mongodb

```

Make sure the ext-mongodb PHP extension is installed and enabled.

Quick start
-----------

[](#quick-start)

```
use Config\Database;

$db = Database::connect();            // Default group from Config\Database
$builder = $db->table('users');       // 'users' collection

// Insert
$builder->insert([
    'email' => 'john@example.com',
    'name'  => 'John',
]);

// Find
$user = $builder->where('email', 'john@example.com')->get()->getFirstRow();

// Update with increment
$builder->where('email', 'john@example.com')
        ->setInc('logins', 1)
        ->update();

// Delete
$builder->where('email', 'john@example.com')->delete();
```

Configuration
-------------

[](#configuration)

You can configure the connection in app/Config/Database.php or via .env.

Example .env:

```
# Default group
database.default.DBDriver = MongoDB

# Option 1: DSN (recommended)
database.default.dsn = mongodb+srv://user:pass@cluster0.mongodb.net/mydatabase?retryWrites=true&w=majority

# Option 2: separate parameters
# database.default.hostname = localhost
# database.default.port = 27017
# database.default.username = user
# database.default.password = pass
# database.default.database = mydatabase

```

Example app/Config/Database.php:

```
public array $default = [
    'DBDriver' => 'MongoDB',
    'dsn'      => 'mongodb://localhost:27017/mydatabase',
    // or hostname/port/username/password/database
];
```

Switch database at runtime:

```
$db->setDatabase('another_db');
```

Using the Query Builder
-----------------------

[](#using-the-query-builder)

- select(\[...\]) — list of fields (default is "\*").
- where()/orWhere()/whereNot()/orWhereNot() — conditions, arrays and expressions supported.
- whereIn()/whereNotIn()/orWhereIn()/orWhereNotIn()
- like()/notLike()/orLike()/orNotLike() — case-insensitive search is supported via $insensitiveSearch flag.
- groupBy()/orderBy()/limit()/offset()
- insert()/insertBatch()/update()/updateBatch()/replace()/delete()
- countAll()/countAllResults()

Mongo-specific methods:

- setInc('field', n)/setDec('field', n) — $inc
- unsetField('field') — $unset
- setOnInsert('field', value) — $setOnInsert
- push('field', value)/pull('field', value)/addToSet('field', value)
- setUpsertFlag(true|false) — upsert for update/replace

Examples:

```
// Projection and sorting
$rows = $db->table('orders')
    ->select(['_id', 'total', 'status'])
    ->whereIn('status', ['new', 'paid'])
    ->orderBy('created_at', 'DESC')
    ->limit(20)
    ->get()
    ->getResult();

// Array operations with push/addToSet
$db->table('users')
   ->where('_id', '65123abc...') // 24-char hex will be auto-converted to ObjectId
   ->addToSet('roles', 'admin')
   ->push('log', ['at' => new \MongoDB\BSON\UTCDateTime(), 'ev' => 'grant'])
   ->update();

// Upsert
$db->table('counters')
   ->where('_id', 'page_views')
   ->setInc('value', 1)
   ->setOnInsert('created_at', new \MongoDB\BSON\UTCDateTime())
   ->setUpsertFlag(true)
   ->update();
```

### Aggregations

[](#aggregations)

Basic aggregates:

```
$stats = $db->table('orders')
    ->selectSum('total', 'sumTotal')
    ->selectAvg('total', 'avgTotal')
    ->selectMax('total', 'maxTotal')
    ->selectMin('total', 'minTotal')
    ->where('status', 'paid')
    ->get()
    ->getFirstRow();
```

For complex pipelines use Query Builder where/group/order/limit chains — the driver will build an equivalent Mongo aggregate. Inspect the built query via getCompiled…:

```
echo $db->table('orders')->where('status', 'paid')->getCompiledSelect();
```

### Transactions

[](#transactions)

The driver supports transactions via standard CodeIgniter methods:

```
$db->transBegin();
try {
    $db->table('wallets')->where('_id', $id)->setDec('balance', 100)->update();
    $db->table('wallets')->where('_id', $id2)->setInc('balance', 100)->update();
    $db->transCommit();
} catch (\Throwable $e) {
    $db->transRollback();
    throw $e;
}
```

Note: transactions require a MongoDB replica set.

Models and Entities
-------------------

[](#models-and-entities)

The driver works with `CodeIgniter\Model` and entity casting.

Example model:

```
use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table      = 'users';
    protected $primaryKey = '_id';
    protected $useSoftDeletes = true;           // soft deletes via deleted_at field
    protected $allowedFields = ['email','name','roles','log'];

    protected $returnType = \App\Entities\User::class; // optional

    protected $casts = [
        '_id'        => 'string',
        'created_at' => 'datetime',
        'roles'      => 'array',
    ];
}
```

Working with ObjectId and dates
-------------------------------

[](#working-with-objectid-and-dates)

- `_id` field: a 24-hex-character string is automatically converted to `MongoDB\BSON\ObjectId`. You may also pass `new ObjectId($hex)` manually if needed.
- Dates: use `MongoDB\BSON\UTCDateTime` or any `DateTimeInterface` (with model/entity casting).

Introspection and schema
------------------------

[](#introspection-and-schema)

- `getFieldNames($collection)` — list of fields according to the collection's validation schema.
- `getFieldData($collection)` — types/constraints from the validator.
- `tableExists($collection)` — check for collection existence.
- Indexes: `_indexData($collection)` returns index information.

Limitations
-----------

[](#limitations)

- No JOINs — use denormalization or aggregation `$lookup` when needed (manually via the collection).
- Raw SQL is not supported; use the Query Builder or access the native collection via `$builder->getCollection()`.
- Some Forge features for RDBMS are unavailable or limited.

Access to native MongoDB collection
-----------------------------------

[](#access-to-native-mongodb-collection)

```
$collection = $db->table('users')->getCollection(); // MongoDB\Collection
$cursor = $collection->find(['status' => 'active']);
```

Error handling and debugging
----------------------------

[](#error-handling-and-debugging)

- `$db->error()` — last error code and message.
- `$db->affectedRows()` — number of affected documents for the last operation.
- `$db->insertID()` — last inserted `_id` (if applicable).
- `getCompiledSelect()/getCompiledUpdate()/…` — see what will be sent to MongoDB.

Tests
-----

[](#tests)

Run locally:

```
composer install
composer test

```

GitHub Actions workflow (php.yml) is configured to run tests automatically. See the badge at the top of this README.

Migrations and seeds
--------------------

[](#migrations-and-seeds)

You can use the standard CI4 mechanisms. Tests contain examples of migrations/seeds for MongoDB (see tests/\_support folder).

License
-------

[](#license)

MIT (see LICENSE file).

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance42

Moderate activity, may be stable

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity15

Early-stage or recently created project

 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.

### Community

Maintainers

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

---

Top Contributors

[![WitER](https://avatars.githubusercontent.com/u/12153717?v=4)](https://github.com/WitER "WitER (18 commits)")

### Embed Badge

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

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

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k117.2M117](/packages/jdorn-sql-formatter)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M87](/packages/propel-propel1)[jfelder/oracledb

Oracle DB driver for Laravel

11518.4k](/packages/jfelder-oracledb)

PHPackages © 2026

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