PHP code example of giginc / cakephp5-driver-mongodb

1. Go to this page and download the library: Download giginc/cakephp5-driver-mongodb 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/ */

    

giginc / cakephp5-driver-mongodb example snippets


'Datasources' => [
    'mongo' => [
        'className' => \Giginc\Mongodb\Database\Connection::class,
        'driver'    => \Giginc\Mongodb\Database\Driver\Mongodb::class,
        'host'      => 'localhost',
        'port'      => 27017,
        'database'  => 'my_database',
        'username'  => '',
        'password'  => '',
        // or a full DSN that wins over host/port/auth:
        // 'uri'    => 'mongodb://user:pass@host:27017/my_database?authSource=admin',
    ],
],

// src/Model/Table/UsersTable.php

declare(strict_types=1);

namespace App\Model\Table;

use Giginc\Mongodb\ORM\Table;

class UsersTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);
        $this->setConnection(ConnectionManager::get('mongo'));
    }

    protected ?string $table = 'users';
}

use App\Model\Table\TestsTable;

$users = new UsersTable();

// Fluent queries
$list = $users->find()
    ->where(['status' => 'active'])
    ->order(['created' => 'DESC'])
    ->limit(10)
    ->toArray();

// Single row by _id
$user = $users->get($id);

// Create / update
$entity = $users->newEntity(['name' => 'alice', 'status' => 'active']);
$users->save($entity);

// Delete
$one = $users->find()
    ->first();
$users->delete($one);