PHPackages                             denchikby/phalcon-mongodb-odm - 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. denchikby/phalcon-mongodb-odm

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

denchikby/phalcon-mongodb-odm
=============================

Phalcon MongoDB ODM

v1.0.6(8y ago)4212.8k↓50%8[3 issues](https://github.com/DenchikBY/Phalcon-MongoDB-ODM/issues)MITPHP

Since Jan 16Pushed 8y ago6 watchersCompare

[ Source](https://github.com/DenchikBY/Phalcon-MongoDB-ODM)[ Packagist](https://packagist.org/packages/denchikby/phalcon-mongodb-odm)[ RSS](/packages/denchikby-phalcon-mongodb-odm/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (2)Versions (8)Used By (0)

Phalcon MongoDB ODM
===================

[](#phalcon-mongodb-odm)

[![Latest Stable Version](https://camo.githubusercontent.com/e4d12af2cab08766df9b306bb1e6902c4fdd85dec78af6f4f677739a9867a097/68747470733a2f2f706f7365722e707567782e6f72672f64656e6368696b62792f7068616c636f6e2d6d6f6e676f64622d6f646d2f762f737461626c653f666f726d61743d666c61742d737175617265)](https://packagist.org/packages/denchikby/phalcon-mongodb-odm)[![Total Downloads](https://camo.githubusercontent.com/864d371c482966367f7a77de2ed673c7374b54fa23223399905ee9596536c897/68747470733a2f2f706f7365722e707567782e6f72672f64656e6368696b62792f7068616c636f6e2d6d6f6e676f64622d6f646d2f646f776e6c6f6164733f666f726d61743d666c61742d737175617265)](https://packagist.org/packages/denchikby/phalcon-mongodb-odm)[![Latest Unstable Version](https://camo.githubusercontent.com/11672d05a5c95205d8d6a128eb5faec15625b932e3a6fbaa02a48ae6df8d877e/68747470733a2f2f706f7365722e707567782e6f72672f64656e6368696b62792f7068616c636f6e2d6d6f6e676f64622d6f646d2f762f756e737461626c653f666f726d61743d666c61742d737175617265)](https://packagist.org/packages/denchikby/phalcon-mongodb-odm)[![License](https://camo.githubusercontent.com/894f40a165ee84ff96445d9b93c2af61970195b09ea6941daca2f2548971e0d0/68747470733a2f2f706f7365722e707567782e6f72672f64656e6368696b62792f7068616c636f6e2d6d6f6e676f64622d6f646d2f6c6963656e73653f666f726d61743d666c61742d737175617265)](https://packagist.org/packages/denchikby/phalcon-mongodb-odm)

Tiny, simple and functional MongoDB ODM library for Phalcon framework for new mongodb php extension
---------------------------------------------------------------------------------------------------

[](#tiny-simple-and-functional-mongodb-odm-library-for-phalcon-framework-for-new-mongodb-php-extension)

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

[](#installation)

Make sure you have the MongoDB PHP driver installed. You can find installation instructions at

Install the latest stable version using composer:

```
composer require denchikby/phalcon-mongodb-odm

```

or

```
{
    "require": {
        "denchikby/phalcon-mongodb-odm": "dev-master"
    }
}

```

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

[](#configuration)

Add settings and service to DI:

```
$di->set('config', function () {
    return new \Phalcon\Config([
        'mongodb' => [
            'host'     => 'localhost',
            'port'     => 27017,
            'database' => 'auto'
        ]
    ]);
}, true);

$di->set('mongo', function () use ($di) {
    $config  = $di->get('config')->mongodb;
    $manager = new \MongoDB\Driver\Manager('mongodb://' . $config->host . ':' . $config->port);
    return $manager;
}, true);
```

Creating Model
--------------

[](#creating-model)

```
use DenchikBY\MongoDB\Model;

class User extends Model {}
```

in this case will be used 'user' collection with same name as model.

To specify another collection name use getSource method:

```
use DenchikBY\MongoDB\Model;

class User extends Model
{
    public static function getSource()
    {
        return 'users';
    }
}
```

Initialize Model
----------------

[](#initialize-model)

To initialize a new model instead of

```
$user = new User;
```

use

```
$user = User::init();
```

Initialize filled model:

```
$user = User::init(['name' => 'DenchikBY']);
```

or

```
$user = User::init()->fill(['name' => 'DenchikBY']);
```

or init and save in db

```
$user = User::create(['name' => 'DenchikBY']);
```

Methods
-------

[](#methods)

To array:

```
$ad = Ads::init()->first();
var_dump($ad->toArray()); // array of all fields
var_dump($ad->toArray(['include' => ['id', 'name']])); // array of specified fields
var_dump($ad->toArray(['exclude' => ['user_id']])); // array of all fields except specified
```

Unset field:

```
$ad = Ads::init()->first();
$ad->unsetField('counters.views');
```

Attributes Casting
------------------

[](#attributes-casting)

It allow you to modify attribute type on setting/filling:

It help to save fields to db with need type, what is very important, cause mongo don't casting types in queries.

Supported types: integer, float, boolean, string, array, object, id

```
class User extends Model
{
    protected static $casts = [
        'age' => 'integer'
    ];
}

$user->age = '20';

var_dump($user->age); => int(20)
```

Casts also work in where methods of builder:

```
User::where('age', '20')->get();
```

age will converted to integer and query will load normally.

Relations
---------

[](#relations)

There are two types of relations: one and many;

Definition:

field =&gt; \[related model, type, local field, foreign field\]

```
public static $relations = [
    'user'     => [Users::class, 'one', 'user_id', '_id'],
    'comments' => [Comments::class, 'many', '_id', 'ad_id']
];
```

Relations can be loaded by two ways:

By one query:

```
Ads::where('views', '>', 1000)->join('user')->join('comments')->get()
```

it will use $lookup operator of aggregation framework.

By several queries, just call attribute with name of key in relations array:

```
$user = User::where('name', 'DenchikBY')->first();
var_dump($user->comments);
```

Scopes
------

[](#scopes)

Scopes help to put common queries to methods:

```
/**
 * @method $this active()
 */
class BaseModel extends Model
{
    public scopeActive($builder)
    {
        return $builder->where('active', 1);
    }
}

$users = User::active()->get();
$ads   = Ads::active()->get();
```

Global scopes
-------------

[](#global-scopes)

This scope will binded to any query of model:

```
class Ads extends Model
{
    public static $globalScopes = ['notDeleted'];

    public function notDeleted($builder)
    {
        return $builder->where('deleted', 0);
    }
}
```

Mutators (getters/setters)
--------------------------

[](#mutators-getterssetters)

Mutators allow modify attributes when you getting, setting or filling it.

For example, when you creating user and set the password, hashing may be defined in model:

```
$user = User::create([
    'name'     => 'DenchikBY',
    'password' => '1234'
]);
```

```
class User extends Model
{
    public function getName($value)
    {
        return ucfirst($value);
    }

    public function setPassword($value)
    {
        return Di::getDefault()->get('security')->hash($value);
    }
}
```

Events
------

[](#events)

Existed events before/after for actions save, create, update, delete.

```
class User extends Model
{
    public function afterCreate()
    {
        Email::send($this->email, 'emails.succeddfull_registration', ['user' => $this]);
    }
}
```

Query Builder
-------------

[](#query-builder)

Query builder could be called clearly or implicitly.

```
$users = User::query()->get();
```

similar

```
$users = User::get();
```

Usage
-----

[](#usage)

```
$builder = User::query();

//allowed operators in where =, !=, >, =, where('name', '=', 'DenchikBY');
//similar
$builder->where('name', 'DenchikBY');

$builder->orWhere('name', 'Denis');

$builder->betweenWhere('age', 20, 30);

$builder->notBetweenWhere('age', 20, 30);

$builder->inWhere('name', ['DenchikBY', 'Denis']);

$builder->notInWhere('name', ['DenchikBY', 'Denis']);

$builder->orderBy('created_at', 'desc');

$builder->limit(2, 1);

//Closing methods:

$users = $builder->get(); // return collection of models

$user = $builder->first(); // return first model without collection

$count = $builder->count(); // run count command, which return int of counted documents

$count = $builder->increment('coins', 10); // increase field in founded documents, return count of them

$count = $builder->decrement('coins', 10);

$count = $builder->update(['banned' => 1]); // update founded documents with specified fields, return count of them

$count = $builder->delete(); // delete founded documents, return count of them

$age = $builder->max('age');

$age = $builder->min('age');

$age = $builder->avg('age');

$total = $builder->sum('age');

$builder->unsetField('counters.views');
```

Advanced Wheres
---------------

[](#advanced-wheres)

For grouping where conditions:

```
$query = Ads::query()->where('auto_id', '567153ea43946846683e77ff')->where(function (Builder $query) {
    $query->where('body', 1)->orWhere('capacity', 2);
});
```

Query Result Collection
-----------------------

[](#query-result-collection)

Every select query will return iterated collection class of models.

```
$collection = Comments::where('ad_id', new \MongoDB\BSON\ObjectId($id))->get();
```

It could be iterated with foreach, or used as array $collection\[0\]-&gt;name;

Methods
-------

[](#methods-1)

Size of collection:

```
$collection->count();
```

Will return array of assocs of each model:

```
$collection->toArray();
```

Return json of array, created by toArray method:

```
$collection->toJson();
```

Eager loading, similar as join:

Will load all for all comments by single query and put necessary into every document.

```
$collection->eager(Users::class, 'user', 'user_id', '_id');
```

Grouping documents to arrays by specific field:

```
$collection->groupBy('user');
```

Keys the collection by the given key (unlike groupBy that value will single model, in groupBy array of models):

```
$collection->keyBy('user');
```

Return array of values specific field of collection:

```
$collection->pluck('user_id');
```

Return associated array of specified key =&gt; value fields:

```
$collection->combine('_id', 'text');
```

Return array of chunked collection by specified size:

```
$collection->chunk(10);
```

###  Health Score

39

—

LowBetter than 86% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community15

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 77.4% 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 ~89 days

Recently: every ~107 days

Total

7

Last Release

3237d ago

### Community

Maintainers

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

---

Top Contributors

[![DenchikBY](https://avatars.githubusercontent.com/u/5912200?v=4)](https://github.com/DenchikBY "DenchikBY (24 commits)")[![uzrnem](https://avatars.githubusercontent.com/u/20123106?v=4)](https://github.com/uzrnem "uzrnem (7 commits)")

---

Tags

buildermongodbmongodb-drivermongodb-odmmongodb-ormodmphalconphalcon-frameworkphpquery-builderphpormodmmongodbphalconmongo

### Embed Badge

![Health badge](/badges/denchikby-phalcon-mongodb-odm/health.svg)

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

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[doctrine/mongodb-odm

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

1.1k23.3M302](/packages/doctrine-mongodb-odm)[mmucklo/queue-bundle

Symfony2/3/4/5 Queue Bundle (for background jobs) supporting Mongo (Doctrine ODM), Mysql (and any Doctrine ORM), RabbitMQ, Beanstalkd, Redis, and ... {write your own}

120839.8k](/packages/mmucklo-queue-bundle)[sokil/php-mongo

PHP Object Document Mapper for MongoDB

239161.5k9](/packages/sokil-php-mongo)[leroy-merlin-br/mongolid

Easy, powerful and ultrafast ODM for PHP and MongoDB.

11234.3k4](/packages/leroy-merlin-br-mongolid)

PHPackages © 2026

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