PHPackages                             purekid/mongodm - 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. purekid/mongodm

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

purekid/mongodm
===============

MongoDB ORM that includes support for references,embed and multilevel inheritance.

1.5.0(9y ago)19925.9k47[19 issues](https://github.com/purekid/mongodm/issues)MITPHP

Since Dec 13Pushed 9y ago23 watchersCompare

[ Source](https://github.com/purekid/mongodm)[ Packagist](https://packagist.org/packages/purekid/mongodm)[ RSS](/packages/purekid-mongodm/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (2)Versions (9)Used By (0)

[![image](https://gist.github.com/purekid/d3fc0980914209ff436b/raw/6719d0b5346aa45f50a4c19ea3d38e619638d3e1/mongodm.png)](https://gist.github.com/purekid/d3fc0980914209ff436b/raw/6719d0b5346aa45f50a4c19ea3d38e619638d3e1/mongodm.png)
========================================================================================================================================================================================================================================

[](#)

[![SensioLabsInsight](https://camo.githubusercontent.com/365313c287ccfe23a6f48d2a3961d3db84b63d57e7f1a287835295ffedbe7070/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f61366165366363362d666533612d346362382d383561662d3836353239613063623463322f6d696e692e706e67)](https://insight.sensiolabs.com/projects/a6ae6cc6-fe3a-4cb8-85af-86529a0cb4c2)[![Build Status](https://camo.githubusercontent.com/3c9884811a46bfe00d601255de167796d71eecf30fb0702cfe480027eb1a8c3e/68747470733a2f2f7365637572652e7472617669732d63692e6f72672f707572656b69642f6d6f6e676f646d2e706e673f6272616e63683d6d6173746572)](http://travis-ci.org/purekid/mongodm)[![Latest Stable Version](https://camo.githubusercontent.com/92df8a34fdf06b8a2a45e3e4a50441e7b39c7fec2c643e369e7dfd2e9c3f97ab/68747470733a2f2f706f7365722e707567782e6f72672f707572656b69642f6d6f6e676f646d2f762f737461626c652e706e67)](https://packagist.org/packages/purekid/mongodm) [![Total Downloads](https://camo.githubusercontent.com/bf1048fdf2c03e8ab3a4044a3064f5dce327b5c53d2693aaabe01e7006f460ee/68747470733a2f2f706f7365722e707567782e6f72672f707572656b69642f6d6f6e676f646d2f646f776e6c6f6164732e706e67)](https://packagist.org/packages/purekid/mongodm) [![License](https://camo.githubusercontent.com/718ba0d4c52e01b61120eeceae8b2403279e5c63ccf30380d1aabeac3cbaa207/68747470733a2f2f706f7365722e707567782e6f72672f707572656b69642f6d6f6e676f646d2f6c6963656e73652e706e67)](https://packagist.org/packages/purekid/mongodm)

- [Introduction](#introduction)
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Setup Database](#setup-database)
- [Basic Usage - CRUD](#model-crud)
- [Relationship - Reference](#relationship---reference)
- [Relationship - Embed](#relationship---embed)
- [Collection](#collection)
- [Inheritance](#inheritance)
- [Other methods](#other-static-methods-in-model)
- [Model Hooks](#model-hooks)
- [Special Thanks](#special-thanks-to)

Introduction
------------

[](#introduction)

Mongodm is a MongoDB ORM that includes support for references,embed and even multilevel inheritance.

Features
--------

[](#features)

- ORM
- Simple and flexible
- Support for embed
- Support for references (lazy loaded)
- Support for multilevel inheritance
- Support for local collection operations

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

[](#requirements)

- PHP 5.3 or greater (Tested for 5.5,5.6,7.0,7.1)
- Mongodb 1.3 or greater
- PHP Mongo extension

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

[](#installation)

### 1. Setup in composer.json:

[](#1-setup-in-composerjson)

```
	{
		"require": {
		    "purekid/mongodm": "dev-master"
		}
	}
```

### 2. Install by composer:

[](#2-install-by-composer)

```
$ php composer.phar update

```

Setup Database
--------------

[](#setup-database)

Database config file (By default it locates at /vendor/purekid/mongodm/config.php)

```
	return array(
        'default' => array(
    		'connection' => array(
    			'hostnames' => 'localhost',
    			'database'  => 'default',
    // 			'username'  => '',
    // 			'password'  => '',
    		)
    	),
    	'production' => array(
    		'connection' => array(
    			'hostnames' => 'localhost',
    			'database'  => 'production',
    			'options' => array('replicaSet' => 'rs0')
    		)
    	)
    );
```

#### Authentication

[](#authentication)

Authentication information is passed in via the options array. If you do not specifiy authSource, then the PHP Mongo Driver will choose the "admin" database.

```
$config =  array( 'connection' => array(
      'hostnames' => ':',
      'database'  => '',
      'options'  => [ "connectTimeoutMS" => 500 , "username" => "admin", "password" => "", "authSource" => "admin"] )
  );

```

### Setup database in application

[](#setup-database-in-application)

1.You can set up configuration using the `MongoDB::setConfigBlock` method.

```
\Purekid\Mongodm\MongoDB::setConfigBlock('default', array(
    'connection' => array(
        'hostnames' => 'localhost',
        'database'  => 'default',
        'options'  => array()
    )
));

//
\Purekid\Mongodm\MongoDB::setConfigBlock('auth', array(
    'connection' => array(
        'hostnames' => 'localhost',
        'database'  => 'authDB',
        'options'  => array()
    )
));
```

2.Or you can duplicate a config file into your project, then define a global constanct 'MONGODM\_CONFIG' with it's location.

```
//in a global initialization place

define('MONGODM_CONFIG',__DIR__."/../config/mongodm.php");
```

### Choose config section with APPLICATION\_ENV

[](#choose-config-section-with-application_env)

Which config section Mongodm use ? Mongodm choose 'default' section by default.

You have two ways to specify section :

1.'$config' attribute in Model , you can find this attribute in example below.

2.With environment constanct 'APPLICATION\_ENV' ,this constanct can be set by webserver,your code or shell environment. In this case,you should set $config='default' or don't declare $config in your own model class.

### Create a model and enjoy it

[](#create-a-model-and-enjoy-it)

```

    use Purekid\Mongodm\Model;

    class User extends Model
    {

        static $collection = "user";

        /** use specific config section **/
        public static $config = 'testing';

        /** specific definition for attributes, not necessary! **/
        protected static $attrs = array(

             // 1 to 1 reference
            'book_fav' => array('model'=>'Purekid\Mongodm\Test\Model\Book','type'=> Model::DATA_TYPE_REFERENCE),
             // 1 to many references
            'books' => array('model'=>'Purekid\Mongodm\Test\Model\Book','type'=> Model::DATA_TYPE_REFERENCES),
            // you can define default value for attribute
            'age' => array('default'=>16,'type'=> Model::DATA_TYPE_INTEGER),
            'money' => array('default'=>20.0,'type'=> Model::DATA_TYPE_DOUBLE),
            'hobbies' => array('default'=>array('love'),'type'=> Model::DATA_TYPE_ARRAY),
            'born_time' => array('type'=> Model::DATA_TYPE_TIMESTAMP),
            'family'=>array('type'=> Model::DATA_TYPE_OBJECT),
            'pet_fav' => array('model'=>'Purekid\Mongodm\Test\Model\Pet','type'=> Model::DATA_TYPE_EMBED),
            'pets' => array('model'=>'Purekid\Mongodm\Test\Model\Pet','type'=> Model::DATA_TYPE_EMBEDS),

        );

        public function setFirstName($name) {
        	$name = ucfirst(strtolower($name));
        	$this->__setter('firstName', $name);
        }

        public function getLastName($name) {
        	$name = $this->__getter('name');
        	return strtoupper($name);
        }

    }
```

### Types supported for model attributes

[](#types-supported-for-model-attributes)

```
    [
	'mixed',  // mixed type
	'string',
	'reference',  // 1 ： 1 reference
	'references', // 1 ： many references
	'embed',
	'embeds',
	'integer',
	'int',  // alias of 'integer'
	'double',     // float
	'timestamp',  // store as MongoTimestamp in Mongodb
	'date',  // store as DateTime
	'boolean',    // true or false
	'array',
	'object'
    ];

    const DATA_TYPE_ARRAY      = 'array';

    const DATA_TYPE_BOOL       = 'bool';
    const DATA_TYPE_BOOLEAN    = 'boolean';

    const DATA_TYPE_DATE       = 'date';

    const DATA_TYPE_DBL        = 'dbl';
    const DATA_TYPE_DOUBLE     = 'double';
    const DATA_TYPE_FLT        = 'flt';
    const DATA_TYPE_FLOAT      = 'float';

    const DATA_TYPE_EMBED      = 'embed';
    const DATA_TYPE_EMBEDS     = 'embeds';

    const DATA_TYPE_INT        = 'int';
    const DATA_TYPE_INTEGER    = 'integer';

    const DATA_TYPE_MIXED      = 'mixed';

    const DATA_TYPE_REFERENCE  = 'reference';
    const DATA_TYPE_REFERENCES = 'references';

    const DATA_TYPE_STR        = 'str';
    const DATA_TYPE_STRING     = 'string';

    const DATA_TYPE_TIMESTAMP  = 'timestamp';

    const DATA_TYPE_OBJ        = 'obj';
    const DATA_TYPE_OBJECT     = 'object';

```

If you put a object instance into a Model attribute and this attribute is undefined in $attrs of Model class,the data of attribute will be omitted when Model saving.

```

    $object = new \stdClass();
    $object->name = 'ooobject';

    $user = new User();
    $user->name = 'michael';
    $user->myobject = $object;    // this attribute will be omitted when saving to DB
    $user->save();
```

Model CRUD
----------

[](#model-crud)

### Create

[](#create)

```
	$user = new User();
	$user->name = "Michael";
	$user->age = 18;
	$user->save();
```

Create with initial value

```
	$user = new User( array('name'=>"John") );
	$user->age = 20;
	$user->save();
```

Create using set method

```
	$user->setLastName('Jones'); // Alias of $user->lastName = 'Jones';
	$user->setFirstName('John'); // Implements setFirstName() method
```

#### Set and get values

[](#set-and-get-values)

You can set/get values via variable `$user->name = "John"` or by method `$user->getName()`.

Set using variable or method

```
 	// no "set" method exists
	$user->lastName = 'Jones';
	$user->setLastName('Jones');

	// "set" method exists implements setFirstName()
	$user->firstName = 'jOhn'; // "John"
	$user->setFirstName('jOhn'); // "John"
```

Get using variable or method

```
 	// "get" method exists implements getLastName()
	print $user->lastName; // "JONES"
	print $user->getLastName(); // "JONES"

	// no "get" method
	print $user->firstName; // "John"
	print $user->setFirstName('John'); // "John"
```

### Update

[](#update)

```
	$user->age = 19;
```

Update attributes by array

```
	$user->update( array('age'=>18,'hobbies'=>array('music','game') ) );
	$user->save();
```

Unset attributes

```
	$user->unset('age');
	$user->unset( array('age','hobbies') );
	//or
	unset($user->age);
```

### Retrieve single record

[](#retrieve-single-record)

```
	$user = User::one( array('name'=>"michael" ) );
```

retrieve one record by MongoId

```
	$id = "517c850641da6da0ab000004";
	$id = new \MongoId('517c850641da6da0ab000004'); //another way
	$user = User::id( $id );
```

### Retrieve records

[](#retrieve-records)

Retrieve records that name is 'Michael' and acount of owned books equals 2

```
	$params = array( 'name'=>'Michael','books'=>array('$size'=>2) );
	$users = User::find($params);     // $users is instance of Collection
	echo $users->count();
```

### Retrieve all records

[](#retrieve-all-records)

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

### Count records

[](#count-records)

```
	$count = User::count(array('age'=>16));
```

### Delete record

[](#delete-record)

```
	$user = User::one();
	$user->delete();
```

Relationship - Reference
------------------------

[](#relationship---reference)

### Lazyload a 1:1 relationship record

[](#lazyload-a-11-relationship-record)

```
	$book = new Book();
	$book->name = "My Love";
	$book->price = 15;
	$book->save();

	// !!!remember you must save book before!!!
	$user->book_fav = $book;
	$user->save();

	// now you can do this
	$user = User::one( array('name'=>"michael" ) );
	echo $user->book_fav->name;
```

### Lazyload 1:many relationship records

[](#lazyload-1many-relationship-records)

```
	$user = User::one();
	$id = $user->getId();

	$book1 = new Book();
	$book1->name = "book1";
	$book1->save();

	$book2 = new Book();
	$book2->name = "book2";
	$book2->save();

	$user->books = array($book1,$book2);
	//also you can
	$user->books = Collection::make(array($book1,$book2));
	$user->save();

	//somewhere , load these books
	$user = User::id($id);
	$books = $user->books;      // $books is a instance of Collection
```

Relationship - Embed
--------------------

[](#relationship---embed)

### Single Embed

[](#single-embed)

```
	$pet = new Pet();
	$pet->name = "putty";

	$user->pet_fav = $pet;
	$user->save();

	// now you can do this
	$user = User::one( array('name'=>"michael" ) );
	echo $user->pet_fav->name;
```

### Embeds

[](#embeds)

```
	$user = User::one();
	$id = $user->getId();

	$pet_dog = new Pet();
	$pet_dog->name = "puppy";
	$pet_dog->save();

	$pet_cat = new Pet();
	$pet_cat->name = "kitty";
	$pet_cat->save();

	$user->pets = array($pet_cat,$pet_dog);
	//also you can
	$user->pets = Collection::make(array($pet_cat,$pet_dog));
	$user->save();

	$user = User::id($id);
	$pets = $user->pets;
```

### Collection

[](#collection)

$users is instance of Collection

```
	$users = User::find(  array( 'name'=>'Michael','books'=>array('$size'=>2) ) );
	$users_other = User::find(  array( 'name'=>'John','books'=>array('$size'=>2) ) );
```

Save

```
    $users->save() ;  // foreach($users as $user) { $user->save(); }
```

Delete

```
    $users->delete() ;  // foreach($users as $user) { $user->delete(); }
```

Count

```
	$users->count();
	$users->isEmpty();
```

Iteration

```
	foreach($users as $user) { }

	// OR use Closure

	$users->each(function($user){

	})
```

Sort

```
	//sort by age desc
	$users->sortBy(function($user){
	    return $user->age;
	});

	//sort by name asc
	$users->sortBy(function($user){
	    return $user->name;
	} , true);

	//reverse collection items
	$users->reverse();
```

Slice and Take

```
	$users->slice(0,1);
	$users->take(2);
```

Map

```
	$func = function($user){
		  		if( $user->age >= 18 ){
		    		$user->is_adult = true;
	        	}
	            return $user;
			};

	$users->map($func)->save();

```

Filter

```
	$func = function($user){
	        	if( $user->age >= 18 ){
	    			return true;
	    		}
			}

	$adults = $users->filter($func); // $adults is a new collection
```

Determine a record exists in the collection by object instance

```
	$john = User::one(array("name"=>"John"));

	$users->has($john)
```

Determine a record exists in the collection by numeric index

```
	$users->has(0)
```

Determine a record exists in the collection by MongoID

```
	$users->has('518c6a242d12d3db0c000007')
```

Get a record by numeric index

```
	$users->get(0)
```

Get a record by MongoID

```
	$users->get('518c6a242d12d3db0c000007')
```

Remove a record by numeric index

```
	$users->remove(0)
```

Remove a record by MongoID

```
	$users->remove('518c6a242d12d3db0c000007')
```

Add a single record to collection

```
	$bob = new User( array("name"=>"Bob"));
	$bob->save();
	$users->add($bob);
```

Add records to collection

```
	$bob = new User( array("name"=>"Bob"));
	$bob->save();
	$lisa = new User( array("name"=>"Lisa"));
	$lisa->save();

	$users->add( array($bob,$lisa) );
```

Merge two collection

```
	$users->add($users_other);  // the collection $users_other appends to end of $users
```

Export data to a array

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

Inheritance
-----------

[](#inheritance)

### Define multilevel inheritable models:

[](#define-multilevel-inheritable-models)

```
	use Purekid\Mongodm\Model;
	namespace Demo;

	class Human extends Model{

		static $collection = "human";

		protected static $attrs = array(
			'name' => array('default'=>'anonym','type'=>'string'),
			'age' => array('type'=>'integer'),
			'gender' => array('type'=>'string'),
			'dad' =>  array('type'=>'reference','model'=>'Demo\Human'),
			'mum' =>  array('type'=>'reference','model'=>'Demo\Human'),
			'friends' => array('type'=>'references','model'=>'Demo\Human'),
		)

	}

	class Student extends Human{

		protected static $attrs = array(
			'grade' => array('type'=>'string'),
			'classmates' => array('type'=>'references','model'=>'Demo\Student'),
		)

	}
```

### Use:

[](#use)

```
	$bob = new Student( array('name'=>'Bob','age'=> 17 ,'gender'=>'male' ) );
	$bob->save();

	$john = new Student( array('name'=>'John','age'=> 16 ,'gender'=>'male' ) );
	$john->save();

	$lily = new Student( array('name'=>'Lily','age'=> 16 ,'gender'=>'female' ) );
	$lily->save();

	$lisa = new Human( array('name'=>'Lisa','age'=>41 ,'gender'=>'female' ) );
	$lisa->save();

	$david = new Human( array('name'=>'David','age'=>42 ,'gender'=>'male') );
	$david->save();

	$bob->dad = $david;
	$bob->mum = $lisa;
	$bob->classmates = array( $john, $lily );
	$bob->save();
```

### Retrieve and check value:

[](#retrieve-and-check-value)

```
	$bob = Student::one( array("name"=>"Bob") );

	echo $bob->dad->name;    // David

	$classmates = $bob->classmates;

	echo $classmates->count(); // 2

	var_dump($classmates->get(0)); // john
```

### Retrieve subclass

[](#retrieve-subclass)

Retrieve all Human records , queries without '\_type' because of it's a toplevel class.

```
    $humans = Human::all();
```

Retrieve all Student records , queries with { "\_type":"Student" } because of it's a subclass.

```
    $students = Student::all();
```

### Retrieve subclass *without* `_type`

[](#retrieve-subclass-without-_type)

To retrieve a record without the `_type` criteria (i.e. `{ "_type":"Student" }`) set:

```
class Student extends \Purekid\Mongodm\Model
{
    protected static $useType = false;

    protected static $collection = 'Student';
}
```

*Make sure to set a collection otherwise you will get results with every `_type`.*

Other static methods in Model
-----------------------------

[](#other-static-methods-in-model)

```
	User::drop() // Drop collection
	User::ensureIndex()  // Add index for collection
```

Model Hooks
-----------

[](#model-hooks)

The following hooks are available:

##### \_\_init()

[](#__init)

Executed after the constructor has finished

##### \_\_preInsert()

[](#__preinsert)

Executed before saving a new record

##### \_\_postInsert()

[](#__postinsert)

Executed after saving a new record

##### \_\_preUpdate()

[](#__preupdate)

Executed before saving an existing record

##### \_\_postUpdate()

[](#__postupdate)

Executed after saving an existing record

##### \_\_preSave()

[](#__presave)

Executed before saving a record

##### \_\_postSave()

[](#__postsave)

Executed after saving a record

##### \_\_preDelete()

[](#__predelete)

Executed before deleting a record

##### \_\_postDelete()

[](#__postdelete)

Executed after deleting a record

Special thanks to
-----------------

[](#special-thanks-to)

[mikelbring](https://github.com/mikelbring)[Paul Hrimiuc](https://github.com/hpaul/)

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance18

Infrequent updates — may be unmaintained

Popularity44

Moderate usage in the ecosystem

Community28

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 70.2% 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 ~234 days

Recently: every ~272 days

Total

6

Last Release

3356d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ba90fe3a7cb9b7037dc3b87ff1bf723612f4755c0653c0c531cdf8fd986521f5?d=identicon)[jrschumacher](/maintainers/jrschumacher)

![](https://www.gravatar.com/avatar/58bde07dbe586bf242d820560ba7a5e4d2f0ed5e6c79256cac2e0e54f84fe97f?d=identicon)[purekid](/maintainers/purekid)

---

Top Contributors

[![purekid](https://avatars.githubusercontent.com/u/1232703?v=4)](https://github.com/purekid "purekid (276 commits)")[![jrschumacher](https://avatars.githubusercontent.com/u/46549?v=4)](https://github.com/jrschumacher "jrschumacher (67 commits)")[![timothy-r](https://avatars.githubusercontent.com/u/3721484?v=4)](https://github.com/timothy-r "timothy-r (25 commits)")[![andreychuk](https://avatars.githubusercontent.com/u/6178862?v=4)](https://github.com/andreychuk "andreychuk (9 commits)")[![wildsurfer](https://avatars.githubusercontent.com/u/1456389?v=4)](https://github.com/wildsurfer "wildsurfer (5 commits)")[![digitalkaoz](https://avatars.githubusercontent.com/u/293591?v=4)](https://github.com/digitalkaoz "digitalkaoz (3 commits)")[![bperel](https://avatars.githubusercontent.com/u/1484692?v=4)](https://github.com/bperel "bperel (2 commits)")[![tusharvikky](https://avatars.githubusercontent.com/u/1810991?v=4)](https://github.com/tusharvikky "tusharvikky (2 commits)")[![dongyaocn](https://avatars.githubusercontent.com/u/12098507?v=4)](https://github.com/dongyaocn "dongyaocn (1 commits)")[![juanfe190](https://avatars.githubusercontent.com/u/11285066?v=4)](https://github.com/juanfe190 "juanfe190 (1 commits)")[![jmartin82](https://avatars.githubusercontent.com/u/152270?v=4)](https://github.com/jmartin82 "jmartin82 (1 commits)")[![amit777](https://avatars.githubusercontent.com/u/2703309?v=4)](https://github.com/amit777 "amit777 (1 commits)")

---

Tags

ormmongodbmongodm

### Embed Badge

![Health badge](/badges/purekid-mongodm/health.svg)

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

###  Alternatives

[omines/datatables-bundle

Symfony DataTables Bundle with native Doctrine ORM, Elastica and MongoDB support

2851.4M6](/packages/omines-datatables-bundle)[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)[h4cc/alice-fixtures-bundle

Symfony2 Bundle for loading fixture data with the Alice library.

76314.2k7](/packages/h4cc-alice-fixtures-bundle)[sammaye/mongoyii

A Yii MongoDB ORM

13681.3k](/packages/sammaye-mongoyii)[denchikby/phalcon-mongodb-odm

Phalcon MongoDB ODM

4212.8k](/packages/denchikby-phalcon-mongodb-odm)

PHPackages © 2026

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