PHP code example of grefon / mongo-model

1. Go to this page and download the library: Download grefon/mongo-model 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/ */

    

grefon / mongo-model example snippets


// Loading composer
;
use MongoModel\MongoDB;

// Initialization of connection to MongoDB
/**
 * @param Client $client - MongoDB Client
 * @param string $base   - name of base
 * @param bool   $debug  - debug
 */
MongoDB::init(new Client('mongodb://127.0.0.1/'), 'baseName', true);

use MongoModel\ModelMongoDB;

/**
 * User Class
 *
 * @property string  userId
 * @property string  surname
 * @property string  name
 * @property string  email
 * @property int     rating
 * @property boolean ban
 * @property string  timeCreate
 * @property string  timeUpdate
 *
 */
class User extends ModelMongoDB
{

    static protected $collection;
    static public    $collectionName = 'users';
    static public    $primaryKey     = 'userId';

    static public    $fieldsModel    = [
        'userId'      => ['string'],
        'surname'     => ['string'],
        'name'        => ['string', '

$user = new User(['name' => 'Will', 'surname' => 'Smith']);
$user->save();

$user = new User;
$user->name = 'Will';
$user->surname = 'Smith';
$user->save();

$user = new User;
$user->save(['name' => 'Will', 'surname' => 'Smith']);

$user = User::new(['name' => 'Will', 'surname' => 'Smith'], false);

$userID = User::new(['userId' => 'user123', 'name' => 'Bob', 'rating' => 15]);

$user = User::get('63399434089c8c26344ff2df');

$user = User::get(['name' => 'Bob', 'rating' => ['$gte' => 10]]);

$user = User::get(['phones.number' => 123456789);

// The first found document with a rating less than zero or banned will be returned
$user = User::get(['$or' => [['rating' => ['$lt' => 0]], ['ban' => true]]]);

if ($user = User::get('63399434089c8c26344ff2df')) {

    $user->rating = '20'; // string will be converted to int
    $user->save(['email' => '[email protected]']);
    
}

$user->email = '[email protected]';
$user->rating = 50;
$user->saveField('rating');

$user->email = '[email protected]';
$user->saveField('rating', 50);

$user->surname = 'TEST';
$user->email = '[email protected]';
$user->rating = 50;

// Saves only rating
$user->saveFields('rating');

// Saves only rating and email
$user->saveFields(['rating', 'email']);

class User extends ModelMongoDB
{

    // ..............................

    function changeEmail(string $email) {
        
        $this->email = $email;
        $this->changedFields[] = 'email';
        return $this;
    
    }
    
    function resetRating() {
        
        $this->rating = 0;
        $this->changedFields[] = 'rating';
        return $this;
    
    }

}

if ($user = User::get('63399434089c8c26344ff2df')) {

    if (!empty($_POST['email'])) {
    
        // Change email
        $user->changeEmail($_POST['email']);
    
    }
    
    // Reset the rating and save the changed object properties in MongoDB
    $user->resetRating()
         ->saveFields();

}

if ($user = User::get('63399434089c8c26344ff2df')) {

    $user->delete();

}

if ($user = User::get('63399434089c8c26344ff2df')) {

    print_r($user->getArray());
    
}

// Will return only properties that have turn only properties that have card and short in their attributes
$user->getArray(['card', 'short']);

$userId = '63399434089c8c26344ff2df';
$email = $_POST['email'] ?? null;
$name = $_POST['name'] ?? null;
// ...................................

// In the first section of code
if ($email) {

    $user = User::getFromCache($userId);
    $user->email = $email;

}

// ...................................

// In the second section of code
if ($name) {

    $user = User::getFromCache($userId);
    $user->name = $name;

}

// ...................................
if ($email or $name) {

    User::getFromCache($userId)->save();

}

// Returns an array of all documents
User::itemsGet(); 

// Returns an array with documents that have _id = 26
User::itemsGet(26); 

// Returns an array with documents that have _id = user_12
User::itemsGet('user_12'); 

// Returns an array with documents that have _id = ObjectId("63399434089c8c26344ff2df")
User::itemsGet('63399434089c8c26344ff2df'); 

// Returns an array with documents that have _id = user_12 or ObjectId("63399434089c8c26344ff2df")
User::itemsGet(['user_12', '63399434089c8c26344ff2df']); 

// Returns an array with documents that have name = Will and surname = Smith
User::itemsGet(['name' => 'Will', 'surname' => 'Smith']);

foreach (User::itemsGet(['rating' => ['$lt' => 10]], null) as $user) {

    $user->rating += 5;
    $user->saveField('rating');

}

foreach (User::itemsGet(['name' => 'Will'], 'rating') as $userId => $rating) {

}

foreach (User::itemsGet(['name' => 'Will'], ['name', 'surname', 'rating']) as $userId => $item) {

    echo $item->name . ' ' . $item->surname . ' has a rating ' . $item->rating;
    // Will Smith has a rating 10
    // Will Duk has a rating 7
    // ..........

}

// Ascending
User::itemsGet(['name' => 'Will'], null, 'rating');

// Descending
User::itemsGet(['name' => 'Will'], null, ['rating', 'DESC']);

// Returns the first 10 documents found
User::itemsGet(null, null, null, 10);

// Returns the found document from 21 to 30
User::itemsGet(null, null, null, [20, 10]);

User::itemsGet(['name' => 'Will'], null, 'rating', 10, ['hint' => 'index_name_rating']);

if (User::itemsHas(['email' => '[email protected]'])) {
    
    die('Email busy');

}

// How many documents have a 'rating' greater than 100
echo User::itemsCount(['rating' => ['$gt' => 100]]);

// We suggest the index and count up to a maximum of 20
echo User::itemsCount(['rating' => ['$gt' => 100]], ['hint' => 'my_index', 'limit' => 20]);

// Delete all documents with 'rating' property less than zero
echo User::itemsDelete(['rating' => ['$lt' => 0]]);

$newUsersID = User::itemsNew(
    [
        [
            'name'   => 'Ben',
            'rating' => 77
        ],
        [
            'name'    => 'Robin',
            'surname' => 'Collins'
        ]
    ],
    true
);

class User extends ModelMongoDB
{

    // ..............................

    static public $fieldsModel = [
        'userId'  => ['string'],
        'surname' => ['string'],                                          // DO NOT track changes
        'name'    => ['string', '           'historyValue' => 'historyValuePhones'
                     ],
        'history' => ['history']                                          // History array
    ];

}

class User extends ModelMongoDB
{

    // ..............................

    protected function checkRecordHistory($changes) {

        return count($this->history) < 100;    
    
    }

}

class User extends ModelMongoDB
{

    // ..............................

    function afterLoad() {
        
        // If the rating in MongoDB was less than 500
        if (empty($this->rating) or $this->rating < 500) {
        
            $this->rating = 500;
        
        }
    
    }
    
    function preSave() {
        
        // If after all the manipulations the rating has become less than -100
        if ($this->rating < -100) {
        
            $this->ban = true;
        
        }
    
    }

}

if ($user = User::get('63399434089c8c26344ff2df')) {

    $user->name = 'Jack';
    echo $user->name; // Jack
    echo $user->getSnapshot('name'); // Will
    echo $user->getSnapshotUpdate('name'); // Will
    
    // Save name Jack
    $user->saveFields('name');
    
    $user->name = 'Bob';
    echo $user->name; // Bob
    echo $user->getSnapshot('name'); // Will
    echo $user->getSnapshotUpdate('name'); // Jack
    
    // Save name Dan
    $user->save(['name' => 'Dan']);
    
    $user->name = 'Test';
    echo $user->name; // Test
    echo $user->getSnapshot('name'); // Will
    echo $user->getSnapshotUpdate('name'); // Dan   
    
}

use MongoModel\MongoDB;

// Ban all users with a rating less than -100
MongoDB::execute(User::getCollection(), 'updateMany', [
    'rating' => ['$lt' => -100]
], [
    '$set' => [
        'ban' => true
    ]
]);

use MongoModel\MongoDB;

print_r(MongoDB::collectionInfo('users'));
json
[
    {
        "code" : 1,
        "phone" : 555331188,
        "number" : 1555331188,
        "formatted" : "(+1) 555331188",
        "timeAdd" : "2022-10-05 17:48:41"
    },
    {
        "code" : 12,
        "phone" : 7774477,
        "number" : 127774477,
        "formatted" : "(+1) 7774477",
        "timeAdd" : "2022-10-05 19:31:02"
    }
]