PHP code example of sokil / php-mongo

1. Go to this page and download the library: Download sokil/php-mongo library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sokil / php-mongo example snippets



$client = new Client($dsn);



$pool = new ClientPool(array(
    'connect1' => array(
        'dsn' => 'mongodb://127.0.0.1',
        'defaultDatabase' => 'db2',
        'connectOptions' => array(
            'connectTimeoutMS' => 1000,
            'readPreference' => \MongoClient::RP_PRIMARY,
        ),
        'mapping' => array(
            'db1' => array(
                'col1' => '\Collection1',
                'col2' => '\Collection2',
            ),
            'db2' => array(
                'col1' => '\Collection3',
                'col2' => '\Collection4',
            )
        ),
    ),
    'connect2' => array(
        'dsn' => 'mongodb://127.0.0.1',
        'defaultDatabase' => 'db2',
        'mapping' => array(
            'db1' => array(
                'col1' => '\Collection5',
                'col2' => '\Collection6',
            ),
            'db2' => array(
                'col1' => '\Collection7',
                'col2' => '\Collection8',
            )
        ),
    ),
));

$connect1Client = $pool->get('connect1');
$connect2Client = $pool->get('connect2');


$database = $client->getDatabase('databaseName');
// or simply
$database = $client->databaseName;


$collection = $database->getCollection('collectionName');
// or simply
$collection = $database->collectionName;


$client->useDatabase('databaseName');
$collection = $client->getCollection('collectionName');



// define class of collection
class CustomCollection extends \Sokil\Mongo\Collection
{

}


/**
 * @var \CustomCollection
 */
$collection = $client
    ->getDatabase('databaseName')
    ->getCollection('collectionName');


$client->map([
    'databaseName'  => [
        'collectionName' => [
            'class' => '\Some\Custom\Collection\Classname',
            'collectionOption1' => 'value1',
            'collectionOption2' => 'value2',
        ]
    ],
]);


// will return 'value1'
$client
    ->getDatabase('databaseName')
    ->getCollection('collectionName')
    ->getOption('collectionOption1');


$client->map([
    'databaseName'  => [
        'collectionName' => [
            'documentClass' => '\Some\Document\Class',
        ]
    ],
]);

// is instance of \Some\Document\Class
$document = $client
    ->getDatabase('databaseName')
    ->getCollection('collectionName')
    ->createDocument();



// map class to collection name
$client->map([
    'databaseName'  => [
        'collectionName' => [
            'class' => \Acme\MyCollection',
        ],
    ],
]);

/**
 * @var \Acme\MyCollection
 */
$collection = $client
    ->getDatabase('databaseName')
    ->getCollection('collectionName');



// map class to collection name
$client->map([
    'databaseName'  => [
        'collectionName' => '\Acme\MyCollection'
    ],
]);

/**
 * @var \Acme\MyCollection
 */
$collection = $client
    ->getDatabase('databaseName')
    ->getCollection('collectionName');


$client->map([
    'databaseName'  => [
        '*' => [
            'class' => '\Acme\Collection\Class\Prefix',
        ],
    ],
]);

/**
 * @var \Acme\Collection\Class\Prefix\CollectionName
 */
$collection = $client
    ->getDatabase('databaseName')
    ->getCollection('collectionName');

/**
 * @var \Acme\Collection\Class\Prefix\CollectionName\SubName
 */
$collection = $client
    ->getDatabase('databaseName')
    ->getCollection('collectionName.subName');


$client->map([
    'databaseName'  => '\Acme\Collection\Class\Prefix',
]);

/**
 * @var \Acme\Collection\Class\Prefix\CollectionName
 */
$collection = $client
    ->getDatabase('databaseName')
    ->getCollection('collectionName');

/**
 * @var \Acme\Collection\Class\Prefix\CollectionName\SubName
 */
$collection = $client
    ->getDatabase('databaseName')
    ->getCollection('collectionName.subName');


$database->map(array(
    '/someCollection(\d)/' => '\Some\Collection\Class',
));


$col1 = $database->getCollection('someCollection1');
$col2 = $database->getCollection('someCollection2');
$col4 = $database->getCollection('someCollection4');


$database->map(array(
    '/someCollection(\d+)/' => '\Some\Collection\Class',
));
$col42 = $database->getCollection('someCollection42');
echo $col1->getOption('regexp')[0]; // someCollection42
echo $col1->getOption('regexp')[1]; // 42


class CustomDocument extends \Sokil\Mongo\Document
{

}


class CustomCollection extends \Sokil\Mongo\Collection
{
    public function getDocumentClassName(array $documentData = null) {
        return '\CustomDocument';
    }
}


class CustomCollection extends \Sokil\Mongo\Collection
{
    public function getDocumentClassName(array $documentData = null) {
        return '\Custom' . ucfirst(strtolower($documentData['type'])) . 'Document';
    }
}


$client->map([
    'databaseName'  => [
        'collectionName1' => [
            'documentClass' => '\CustomDocument',
        ],
        'collectionName2' => function(array $documentData = null) {
            return '\Custom' . ucfirst(strtolower($documentData['type'])) . 'Document';
        },
        'collectionName3' => [
            'documentClass' => function(array $documentData = null) {
                return '\Custom' . ucfirst(strtolower($documentData['type'])) . 'Document';
            },
        ],
    ],
]);


class CustomDocument extends \Sokil\Mongo\Document
{
    protected $schema = [
        '


class CustomDocument extends \Sokil\Mongo\Document
{
    protected $_data = [
        '


class CustomDocument extends \Sokil\Mongo\Document
{
    public function rules()
    {
        return array(
            array('email,password', ' => array('admin', 'manager', 'user')),
            array('contract_number', 'numeric', 'message' => 'Custom error message, shown by getErrors() method'),
            array('contract_number' ,'null', 'on' => 'SCENARIO_WHERE_CONTRACT_MUST_BE_NULL'),
            array('code' ,'regexp', '#[A-Z]{2}[0-9]{10}#')
        );
    }
}


$document->setScenario('register');


public function rules()
    {
        return array(
            array('field' ,'null', 'on' => 'register,update'),
        );
    }


public function rules()
    {
        return array(
            array('field' ,'null', 'except' => 'register,update'),
        );
    }

try {
    $document->save();
} catch (\Sokil\Mongo\Document\InvalidDocumentException $e) {
    // get validation errors
    var_dump($document->getErrors());
    // get document instance from exception
    var_dump($e->getDocument()->getErrors());
}

if ($document->isValid())
    $document->save();
} else {
    var_dump($document->getErrors());
}


try {
    $document->save();
} catch(\Sokil\Mongo\Document\InvalidDocumentException $e) {
    $e->getDocument()->getErrors();
}

$document->save(false);


$document->triggerError('someField', 'email', 'E-mail must be at domain example.com');


class CustomDocument extends \Sokil\Mongo\Document
{
    punlic function rules()
    {
        return array(
            array(
                'email',
                'uniqueFieldValidator',
                'message' => 'E-mail must be unique in collection'
            ),
        );
    }

    /**
     * Validator
     */
    public function uniqueFieldValidator($fieldName, $params)
    {
        // Some logic of checking unique mail.
        //
        // Before version 1.7 this method must return true if validator passes,
        // and false otherwise.
        //
        // Since version 1.7 this method return no values and must call
        // Document::addError() method to add error into stack.
    }
}


namespace Vendor\Mongo\Validator;

/**
 * Validator class
 */
class MyOwnEqualsValidator extends \Sokil\Mongo\Validator
{
    public function validateField(\Sokil\Mongo\Document $document, $fieldName, array $params)
    {
        if (!$document->get($fieldName)) {
            return;
        }

        if ($document->get($fieldName) === $params['to']) {
            return;
        }

        if (!isset($params['message'])) {
            $params['message'] = 'Field "' . $fieldName . '" must be equals to "' . $params['to'] . '" in model ' . get_called_class();
        }

        $document->addError($fieldName, $this->getName(), $params['message']);
    }
}

/**
 * Registering validator in document
 */

class SomeDocument extends \Sokil\Mongo\Document
{
    public function beforeConstruct()
    {
        $this->addValidatorNamespace('Vendor\Mongo\Validator');
    }

    public function rules()
    {
        return array(
            // 'my_own_equals' converts to 'MyOwnEqualsValidator' class name
            array('field', 'my_own_equals', 'to' => 42, 'message' => 'Not equals'),
        );
    }
}


$document = $collection->getDocument('5332d21b253fe54adf8a9327');


$document = $collection->getDocument(
    '5332d21b253fe54adf8a9327',
    function(\Sokil\Mongo\Cursor $cursor) {
        // get document only if active
        $cursor->where('status', 'active');
        // slice embedded documents
        $cursor->slice('embdocs', 10, 30);
    }
);


$document = $collection->createDocument();


$document = $collection->createDocument([
    'param1' => 'value1',
    'param2' => 'value2'
]);


$document->quiredField(); // defaultValue

$document->someField; // ['subDocumentField' => 'value']
$document->get('someField'); // ['subDocumentField' => 'value']
$document->getSomeField(); // ['subDocumentField' => 'value']
$document->get('someField.subDocumentField'); // 'value'

$document->get('some.unexisted.subDocumentField'); // null


$document->someField = 'someValue'; // {someField: 'someValue'}
$document->set('someField', 'someValue'); // {someField: 'someValue'}
$document->set('someField.sub.document.field', 'someValue'); // {someField: {sub: {document: {field: {'someValue'}}}}}
$document->setSomeField('someValue');  // {someField: 'someValue'}



$document->push('field', 1);
$document->push('field', 2);

$document->get('field'); // return [1, 2]



/**
 * Profile class
 */
class Profile extends \Sokil\Mongo\Structure
{
    public function getBirthday() { return $this->get('birthday'); }
    public function getGender() { return $this->get('gender'); }
    public function getCountry() { return $this->get('country'); }
    public function getCity() { return $this->get('city'); }
}

/**
 * User model
 */
class User extends \Sokil\Mongo\Document
{
    public function getProfile()
    {
        return $this->getObject('profile', '\Profile');
    }
}


$birthday = $user->getProfile()->getBirthday();

/**
 * Profile class
 */
class Profile extends \Sokil\Mongo\Structure
{
    public function getBirthday() { return $this->get('birthday'); }

    public function rules()
    {
        return array(
            array('birthday', '

try {
    $user->set('profile', $profile);
} catch (InvalidDocumentException $e) {
    $e->getDocument()->getErrors();
}


class Comment extends \Sokil\Mongo\Structure
{
    public function getAuthor() { return $this->get('author'); }
    public function getText() { return $this->get('text'); }
    public function getDate() { return $this->get('date')->sec; }
}




class Post extends \Sokil\Mongo\Document
{
    public function getComments()
    {
        return $this->getObjectList('comments', '\Comment');
    }
}


$collection->find()->slice('comments', $limit, $offset)->findAll();


$document = $collection->getDocument('54ab8585c90b73d6949d4159', function(Cursor $cursor) {
    $cursor->slice('comments', $limit, $offset);
});



$post->push('comments', new Comment(['author' => 'John Doe']));
$post->push('comments', new Comment(['author' => 'Joan Doe']));

class EmbeddedDocument extends Structure()
{
    public function rules() {}
}

$embeddedDocument = new EmbeddedDocument();
// auto validation
try {
    $document->set('some', embeddedDocument);
    $document->addToSet('some', embeddedDocument);
    $document->push('some', embeddedDocument);
} catch (InvalidDocumentException $e) {
    
}

// manual validation
if ($embeddedDocument->isValid()) {
    $document->set('some', embeddedDocument);
    $document->addToSet('some', embeddedDocument);
    $document->push('some', embeddedDocument);
}


$collection->getDocumentByReference(array('$ref' => 'col', '$id' => '23ef12...ff452'));
$database->getDocumentByReference(array('$ref' => 'col', '$id' => '23ef12...ff452'));


$relatedDocument = $this->collection->createDocument(array('param' => 'value'))->save();
$document = $this->collection
    ->createDocument()
    ->setReference('related', $relatedDocument)
    ->save();



$relatedDocument = $document->getReferencedDocument('related');




$relatedDocument = $this->collection->createDocument(array('param' => 'value'))->save();
$document = $this->collection
    ->createDocument()
    ->pushReference('related', $relatedDocument)
    ->save();



$foundRelatedDocumentList = $document->getReferencedDocumentList('related');




// create new document and save
$document = $collection
    ->createDocument(['param' => 'value'])
    ->save();

// load existed document, modify and save
$document = $collection
    ->getDocument('23a4...')
    ->set('param', 'value')
    ->save();


$collection->insert(['param' => 'value']);


$collection->update($expression, $data, $options);


$collection->update(
    function(\Sokil\Mongo\Expression $expression) {
        $expression->where('status', 'active');
    },
    function(\Sokil\Mongo\Operator $operator) {
        $operator->increment('counter');
    },
    array(
        'multiple' => true,
    )
);


$collection->batchInsert(array(
    array('i' => 1),
    array('i' => 2),
));


$collection
    ->createBatchInsert()
    ->insert(array('i' => 1))
    ->insert(array('i' => 2))
    ->execute('majority');



$collection->batchUpdate(
    function(\Sokil\Mongo\Expression $expression) {
        return $expression->where('field', 'value');
    },
    ['field' => 'new value']
);



$collection->batchUpdate([], array('field' => 'new value'));


$collection->batchUpdate(
    [],
    function(Operator $operator) {
        $operator->renameField('param', 'renamedParam');
    }
);


$collection
    ->createBatchUpdate()
    ->update(
        array('a' => 1),
        array('$set' => array('b' => 'updated1')),
        $multiple,
        $upsert
    )
    ->update(
        $collection->expression()->where('a', 2),
        $collection->operator()->set('b', 'updated2'),
        $multiple,
        $upsert
    )
    ->update(
        function(Expression $e) { $e->where('a', 3); },
        function(Operator $o) { $o->set('b', 'updated3'); },
        $multiple,
        $upsert
    )
    ->execute('majority');


// to new collection of same database
$collection
    ->find()
    ->where('condition', 1)
    ->copyToCollection('newCollection');

// to new collection in new database
$collection
    ->find()
    ->where('condition', 1)
    ->copyToCollection('newCollection', 'newDatabase');


// to new collection of same database
$collection
    ->find()
    ->where('condition', 1)
    ->moveToCollection('newCollection');

// to new collection in new database
$collection
    ->find()
    ->where('condition', 1)
    ->moveToCollection('newCollection', 'newDatabase');


$cursor = $collection
    ->find()
    ->fields(['name', 'age'])
    ->where('name', 'Michael')
    ->whereGreater('age', 29)
    ->whereIn('interests', ['php', 'snowboard', 'traveling'])
    ->skip(20)
    ->limit(10)
    ->sort([
        'name'  => 1,
        'age'   => -1,
    ]);


$cursor = $collection
    ->find()
    ->whereOr(
        $collection->expression()->where('field1', 50),
        $collection->expression()->where('field2', 50),
    );


foreach($cursor as $documentId => $document) {
    echo $document->get('name');
}


$result = $cursor->findAll();


$document = $cursor->findOne();


$document = $cursor->findRandom();


$columnValues = $cursor->pluck('some.field.name');


$result = $collection->find()->map(function(Document $document) {
    return $document->param;
});


$result = $collection->find()->filter(function(Document $document) {
    return $document->param % 2;
});


$collection->find()
    ->getResultSet()
    ->filter(function($doc) { return $doc->param % 2 })
    ->filter(function($doc) { return $doc->param > 6 })
    ->map(function($item) {
        $item->param = 'update' . $item->param;
        return $item;
    });



$cursor->setBatchSize(20);
 
$collection->find()->where('name', 'Michael')->setClientTimeout(4200);

$collection->find()->where('name', 'Michael')->setServerTimeout(4200);


// return all distinct values
$values = $collection->getDistinct('country');


// by array
$collection->getDistinct('country', array('age' => array('$gte' => 25)));
// by object
$collection->getDistinct('country', $collection->expression()->whereGreater('age', 25));
// by callable
$collection->getDistinct('country', function($expression) { return $expression->whereGreater('age', 25); });



// define expression
class UserExpression extends \Sokil\Mongo\Expression
{
    public function whereAgeGreaterThan($age)
    {
        $this->whereGreater('age', (int) $age);
    }
}



$client->map([
    'myDb' => [
        'user' => [
            'class' => '\UserCollection',
            'expressionClass' => '\UserExpression',
        ],
    ],
]);



// define expression in collection
class UserCollection extends \Sokil\Mongo\Collection
{
    protected $_queryExpressionClass = 'UserExpression';
}


// use custom method for searching
$collection = $db->getCollection('user'); // instance of UserCollection
$queryBuilder = $collection->find(); // instance of UserExpression

// now methods available in query buider
$queryBuilder->whereAgeGreaterThan(18)->fetchRandom();

// since v.1.3.2 also supported query builder configuration through callable:
$collection
    ->find(function(UserExpression $e) {
        $e->whereAgeGreaterThan(18);
    })
    ->fetchRandom();



$document1 = $collection->find()->whereGreater('age' > 18)->findOne();
$document2 = $collection->find()->where('gender', 'male')->findOne();

$document1->name = 'Mary';
echo $document2->name; // Mary


$collection->map([
    'someDb' => [
        'someCollection', array(
            'documentPool' => false,
        ),
    ],
]);




$collection->disableDocumentPool();



$collection->enableDocumentPool();



$collection->isDocumentPoolEnabled();



$collection->clearDocumentPool();



$collection->isDocumentPoolEmpty();



$document->refresh();



$queryBuilder = $this->collection
    ->find()
    ->field('_id')
    ->field('interests')
    ->sort(array(
        'age' => 1,
        'gender' => -1,
    ))
    ->limit(10, 20)
    ->whereAll('interests', ['php', 'snowboard']);

$hash = $queryBuilder->getHash(); // will return 508cc93b371c222c53ae90989d95caae

if($cache->has($hash)) {
    return $cache->get($hash);
}

$result = $queryBuilder->findAll();

$cache->set($hash, $result);



// creates index on location field
$collection->ensure2dSphereIndex('location');
// cerate compound index
$collection->ensureIndex(array(
    'location' => '2dsphere',
    'name'  => -1,
));



$document->setGeometry(
    'location',
    new \GeoJson\Geometry\Point(array(30.523400000000038, 50.4501))
);

$document->setGeometry(
    'location',
    new \GeoJson\Geometry\Polygon(array(
        array(24.012228, 49.831485), // Lviv
        array(36.230376, 49.993499), // Harkiv
        array(34.174927, 45.035993), // Simferopol
        array(24.012228, 49.831485), // Lviv
    ))
);




// Point
$document->setPoint('location', 30.523400000000038, 50.4501);
// LineString
$document->setLineString('location', array(
    array(30.523400000000038, 50.4501),
    array(36.230376, 49.993499),
));
// Polygon
$document->setPolygon('location', array(
    array(
        array(24.012228, 49.831485), // Lviv
        array(36.230376, 49.993499), // Harkiv
        array(34.174927, 45.035993), // Simferopol
        array(24.012228, 49.831485), // Lviv
    ),
));
// MultiPoint
$document->setMultiPoint('location', array(
    array(24.012228, 49.831485), // Lviv
    array(36.230376, 49.993499), // Harkiv
    array(34.174927, 45.035993), // Simferopol
));
// MultiLineString
$document->setMultiLineString('location', array(
    // line string 1
    array(
        array(34.551416, 49.588264), // Poltava
        array(35.139561, 47.838796), // Zaporizhia
    ),
    // line string 2
    array(
        array(24.012228, 49.831485), // Lviv
        array(34.174927, 45.035993), // Simferopol
    )
));
// MultiPolygon
$document->setMultyPolygon('location', array(
    // polygon 1
    array(
        array(
            array(24.012228, 49.831485), // Lviv
            array(36.230376, 49.993499), // Harkiv
            array(34.174927, 45.035993), // Simferopol
            array(24.012228, 49.831485), // Lviv
        ),
    ),
    // polygon 2
    array(
        array(
            array(24.012228, 49.831485), // Lviv
            array(36.230376, 49.993499), // Harkiv
            array(34.174927, 45.035993), // Simferopol
            array(24.012228, 49.831485), // Lviv
        ),
    ),
));
// GeometryCollection
$document->setGeometryCollection('location', array(
    // point
    new \GeoJson\Geometry\Point(array(30.523400000000038, 50.4501)),
    // line string
    new \GeoJson\Geometry\LineString(array(
        array(30.523400000000038, 50.4501),
        array(24.012228, 49.831485),
        array(36.230376, 49.993499),
    )),
    // polygon
    new \GeoJson\Geometry\Polygon(array(
        // line ring 1
        array(
            array(24.012228, 49.831485), // Lviv
            array(36.230376, 49.993499), // Harkiv
            array(34.174927, 45.035993), // Simferopol
            array(24.012228, 49.831485), // Lviv
        ),
        // line ring 2
        array(
            array(34.551416, 49.588264), // Poltava
            array(32.049226, 49.431181), // Cherkasy
            array(35.139561, 47.838796), // Zaporizhia
            array(34.551416, 49.588264), // Poltava
        ),
    )),
));



$collection->find()->nearPoint('location', 34.551416, 49.588264, 1000);

composer 

composer 

composer 

composer 

composer 
javascript
{
    "title": "Storing embedded documents",
    "text": "MongoDb allows to atomically modify embedded documents",
    "comments": [
        {
            "author": "MadMike42",
            "text": "That is really cool",
            "date": ISODate("2015-01-06T06:49:41.622Z"
        },
        {
            "author": "beebee",
            "text": "Awesome!!!11!",
            "date": ISODate("2015-01-06T06:49:48.622Z"
        },
    ]
}
php

// serch distance less 100 meters
$collection->find()->nearPoint('location', 34.551416, 49.588264, array(null, 1000));
// search distabce between 100 and 1000 meters
$collection->find()->nearPoint('location', 34.551416, 49.588264, array(100, 1000));
// search distabce greater than 1000 meters
$collection->find()->nearPoint('location', 34.551416, 49.588264, array(1000, null));
php

$collection->find()->nearPointSpherical('location', 34.551416, 49.588264, 1000);
php

$this->collection
    ->find()
    ->intersects('link', new \GeoJson\Geometry\LineString(array(
        array(30.5326905, 50.4020355),
        array(34.1092134, 44.946798),
    )))
    ->findOne();
php

$point = $this->collection
    ->find()
    ->within('point', new \GeoJson\Geometry\Polygon(array(
        array(
            array(24.0122356, 49.8326891), // Lviv
            array(24.717129, 48.9117731), // Ivano-Frankivsk
            array(34.1092134, 44.946798), // Simferopol
            array(34.5572385, 49.6020445), // Poltava
            array(24.0122356, 49.8326891), // Lviv
        )
    )))
    ->findOne();
php

$this->collection
    ->find()
    ->withinCircle('point', 28.46963, 49.2347, 0.001)
    ->findOne();
php

$point = $this->collection
    ->find()
    ->withinCircleSpherical('point', 28.46963, 49.2347, 0.001)
    ->findOne();
php

$point = $this->collection
    ->find()
    ->withinBox('point', array(0, 0), array(10, 10))
    ->findOne();
php

$point = $this->collection
    ->find()
    ->withinPolygon(
        'point',
        array(
            array(0, 0),
            array(0, 10),
            array(10, 10),
            array(10, 0),
        )
    )
    ->findOne();
php


// one field
$collection->ensureFulltextIndex('somefield');

// couple of fields
$collection->ensureFulltextIndex(['somefield1', 'somefield2']);
php


$collection->find()->whereText('string searched in all fulltext fields')->findAll();
php

$paginator = $collection->find()->where('field', 'value')->paginate(3, 20);
$totalDocumentNumber = $paginator->getTotalRowsCount();
$totalPageNumber = $paginator->getTotalPagesCount();

// iterate through documents
foreach($paginator as $document) {
    echo $document->getId();
}
php

$persistence = $client->createPersistence();
php

$persistence->persist($document1);
$persistence->persist($document2);

$persistence->remove($document3);
$persistence->remove($document4);
php

$persistence->detach($document1);
$persistence->detach($document3);
php

$persistence->clear();
php

$persistence->flush();
php

$collection->delete();
php

$document->delete();
php


$collection->batchDelete($collection->expression()->where('param', 'value'));
// deprecated since 1.13
$collection->deleteDocuments($collection->expression()->where('param', 'value'));
php

$batch = $collection->createBatchDelete();
$batch
    ->delete(array('a' => 2))
    ->delete($collection->expression()->where('a', 4))
    ->delete(function(Expression $e) { $e->where('a', 6); })
    ->execute();
php

$aggregator = $collection->createAggregator();
php

// through array
$aggregator->match(array(
    'field' => 'value'
));
// through callable
$aggregator->match(function($expression) {
    $expression->whereLess('date', new \MongoDate);
});
php

/**
 * @var array list of aggregation results
 */
$result = $aggregator->aggregate();
// or
$result = $collection->aggregate($aggregator);
php

// by array
$collection->aggregate(array(
    array(
        '$match' => array(
            'field' => 'value',
        ),
    ),
));
// or callable
$collection->aggregate(function($aggregator) {
    $aggregator->match(function($expression) {
        $expression->whereLess('date', new \MongoDate);
    });
});
php


// as argument of Pipeline::aggregate
$collection->createAggregator()->match()->group()->aggregate($options);

// as argument of Collection::aggregate
$collection->aggregate($pipelines, $options);

// as calling of Pipeline methods
$collection
    ->createAggregator()
    ->explain()
    ->allowDiskUse()
    ->setBatchSize(100);
php


// set explain option
$collection->aggregate($pipelines, ['explain' => true]);

// or configure pipeline
$collection->createAggregator()->match(...)->group(...)->explain()->aggregate();
php


// set as argument
$asCursor = true;
$collection->aggregate($pipelines, $options, $asCursor);

// or call method
$cursor = $collection->createAggregator()->match()->group()->aggregateCursor();
php

$listener = function(
    \Sokil\Mongo\Event $event, // instance of event
    string $eventName, // event name
    \Symfony\Component\EventDispatcher\EventDispatcher $eventDispatcher // instance of dispatcher
) {}
php

$document->attachEvent('myOwnEvent', $listener, $priority);
php

$document->onMyOwnEvent($listener, $priority);
// which is equals to
$this->attachEvent('myOwnEvent', $listener, $priority);
php

class CustomDocument extends \Sokil\Mongo\Document
{
    public function beforeConstruct()
    {
        $this->onBeforeSave(function() {
            $this->set('date' => new \MongoDate);
        });
    }
}
php

$this->triggerEvent('myOwnEvent');
php

// create class
class OwnEvent extends \Sokil\Mongo\Event {
    public $status;
}

// define listener
$document->attachEvent('someEvent', function(\OwnEvent $event) {
    echo $event->status;
});

// configure event
$event = new \OwnEvent;
$event->status = 'ok';

// trigger event
$this->triggerEvent('someEvent', $event);
php

$document->onBeforeSave(function(\Sokil\Mongo\Event $event) {
    if($this->get('field') === 42) {
        $event->cancel();
    }
})
->save();
php

class SomeBehavior extends \Sokil\Mongo\Behavior
{
    public function return42()
    {
        return 42;
    }
}
php

class SomeBehavior extends \Sokil\Mongo\Behavior
{
    public function getOwnerParam($selector)
    {
        return $this->getOwner()->get($selector);
    }
}
php

class CustomDocument extends \Sokil\Mongo\Document
{
    public function behaviors()
    {
        return [
            '42behavior' => '\SomeBehavior',
        ];
    }
}
php

// single behavior
$document->attachBehavior('42behavior', '\SomeBehavior');
// set of behaviors
$document->attachBehaviors([
    '42behavior' => '\SomeBehavior',
]);
php

// class name
$document->attachBehavior('42behavior', '\SomeBehavior');

// array with parameters
$document->attachBehavior('42behavior', [
    'class'     => '\SomeBehavior',
    'param1'    => 1,
    'param2'    => 2,
]);

// Behavior instance
$document->attachBehavior('42behavior', new \SomeBehavior([
    'param1'    => 1,
    'param2'    => 2,
]);
php

echo $document->return42();
php


$collection->map([
    'someDb' => [
        'someCollection', array(
            'relations'     => array(
                'someRelation'   => array(self::RELATION_HAS_ONE, 'profile', 'user_id'),
            ),
        ),
    ],
]);
php

class User extends \Sokil\Mongo\Document
{
    protected $schema = [
        'email'     => null,
        'password'  => null,
    ];

    public function relations()
    {
        return [
            'profileRelation' => [self::RELATION_HAS_ONE, 'profile', 'user_id'],
        ];
    }
}

class Profile extends \Sokil\Mongo\Document
{
    protected $schema = [
        'name' => [
            'last'  => null,
            'first' => null,
        ],
        'age'   => null,
    ];

    public function relations()
    {
        return [
            'userRelation' => [self::RELATION_BELONGS, 'user', 'user_id'],
        ];
    }
}
php

$user = $userColletion->getDocument('234...');
echo $user->profileRelation->get('age');

$profile = $profileCollection->getDocument('234...');
echo $pfofile->userRelation->get('email');
php

class User extends \Sokil\Mongo\Document
{
    protected $schema = [
        'email'     => null,
        'password'  => null,
    ];

    public function relations()
    {
        return [
            'postsRelation' => [self::RELATION_HAS_MANY, 'posts', 'user_id'],
        ];
    }
}

class Posts extends \Sokil\Mongo\Document
{
    protected $schema = [
        'user_id' => null,
        'message'   => null,
    ];

    public function relations()
    {
        return [
            'userRelation' => [self::RELATION_BELONGS, 'user', 'user_id'],
        ];
    }

    public function getMessage()
    {
        return $this->get('message');
    }
}
php

foreach($user->postsRelation as $post) {
    echo $post->getMessage();
}
php


// this document contains field 'driver_id' where array of ids stored
class CarDocument extends \Sokil\Mongo\Document
{
    protected $schema = [
        'brand' => null,
    ];

    public function relations()
    {
        return array(
            'drivers'   => array(self::RELATION_MANY_MANY, 'drivers', 'driver_id', true),
        );
    }
}

class DriverDocument extends \Sokil\Mongo\Document
{
    protected $schema = [
        'name' => null,
    ];

    public function relations()
    {
        return array(
            'cars'    => array(self::RELATION_MANY_MANY, 'cars', 'driver_id'),
        );
    }
}
php

foreach($car->drivers as $driver) {
    echo $driver->name;
}
php

$car->addRelation('drivers', $driver);
php

$car->removeRelation('drivers', $driver);
php

// in constructor
$client = new Client($dsn, array(
    'readPreference' => 'nearest',
));

// by passing to \Sokil\Mongo\Client instance
$client->readNearest();

// by passing to database
$database = $client->getDatabase('databaseName')->readPrimaryOnly();

// by passing to collection
$collection = $database->getCollection('collectionName')->readSecondaryOnly();
php


// by passing to \Sokil\Mongo\Client instance
$client->setMajorityWriteConcern(10000);

// by passing to database
$database = $client->getDatabase('databaseName')->setMajorityWriteConcern(10000);

// by passing to collection
$collection = $database->getCollection('collectionName')->setWriteConcern(4, 1000);
php

$numOfElements = 10;
$sizeOfCollection = 10*1024;
$collection = $database->createCappedCollection('capped_col_name', $numOfElements, $sizeOfCollection);
php

$collection = $database->createCappedCollection('capped_col_name', $numOfElements, $sizeOfCollection);
$stats = $database->executeCommand(['collstat' => 'capped_col_name']);
php

$queue = $database->getQueue('channel_name');
$queue->enqueue('world');
$queue->enqueue(['param' => 'value']);
php

$queue->enqueue('hello', 10);
php

$queue = $database->getQueue('channel_name');
echo $queue->dequeue(); // hello
echo $queue->dequeue(); // world
echo $queue->dequeue()->get('param'); // value
php

$queue = $database->getQueue('channel_name');
echo count($queue);
bash
composer 
php

$imagesFS = $database->getGridFS('image');
$cssFS = $database->getGridFS('css');
php

$id = $imagesFS->storeFile('/home/sokil/images/flower.jpg');
php

$id1 = $imagesFS->storeBytes('some text content');
$id2 = $imagesFS->storeBytes(file_get_contents('/home/sokil/images/flower.jpg'));
php

$id1 = $imagesFS->storeFile('/home/sokil/images/flower.jpg', [
    'category'  => 'flower',
    'tags'      => ['flower', 'static', 'page'],
]);

$id2 = $imagesFS->storeBytes('some text content', [
    'category' => 'books',
]);
php

$imagesFS->getFileById('6b5a4f53...42ha54e');
php

foreach($imagesFS->find()->where('category', 'books') as $file) {
    echo $file->getFilename();
}
php

$imagesFS->deleteFileById('6b5a4f53...42ha54e');
php

// dump binary data to file
$file->dump($filename);

// get binary data
$file->getBytes();

// get resource
$file->getResource();
php

// define mapping of prefix to GridFS class
$database->map([
    'GridFSPrefix' => '\GridFSClass',
]);

// define GridFSFile class
class GridFSClass extends \Sokil\Mongo\GridFS
{
    public function getFileClassName(\MongoGridFSFile $fileData = null)
    {
        return '\GridFSFileClass';
    }
}

// define file class
class GridFSFileClass extends \Sokil\Mongo\GridFSFile
{
    public function getMetaParam()
    {
        return $this->get('meta.param');
    }
}

// get file as instance of class \GridFSFileClass
$database->getGridFS('GridFSPrefix')->getFileById($id)->getMetaParam();
php

// througn protected property
class MyCollection extends \Sokil\Mongo\Collection
{
    protected $versioning = true;
}

// througn method
$collection = $database->getCollection('my');
$collection->enableVersioning();

// through mapping
$database->map('someCollectionName', [
    'versioning' => true,
]);
php

if($collection->isVersioningEnabled()) {}
php

// get all revisions
$document->getRevisions();

// get slice of revisions
$limit = 10;
$offset = 15;
$document->getRevisions($limit, $offset);
php

$revision = $document->getRevision($revisionKey);
php

$count = $document->getRevisionsCount();
php

$document->clearRevisions();
php

$document->getRevision($revisionKey)->getDocument();

echo $document->property;
echo $document->getRevision($revisionKey)->property;
php

// return timestamp
echo $document->getRevision($revisionKey)->getDate();
// return formatted date string
echo $document->getRevision($revisionKey)->getDate('d.m.Y H:i:s');
php

$collection->ensureIndex('field', [ 'unique' => true ]);
php

$collection->ensureUniqueIndex('field');
php

$collection->ensureSparseIndex('field');
php

$collection->ensureTTLIndex('field');
php

$collection->ensureIndex(['field' => 1]);
php

$collection->ensureIndex(['field1' => 1, 'field2' => -1]);
php

class MyCollection extends \Sokil\Mongo\Collection
{
    protected $_index = array(
        array(
            'keys' => array('field1' => 1, 'field2' => -1),
            'unique' => true
        ),
    );
}
php

$collection = $database->getCollection('myCollection')->initIndexes();
php

$collection->find()->where('field', 1)->hind(array('field' => 1));
php

$collection->ensureTTLIndex('createDate', 1000);
php


// Get cache instance
$cache = $database->getCache('some_namespace');