PHP code example of phpdot / mongodb

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

    

phpdot / mongodb example snippets


use PHPdot\MongoDB\MongoConnection;
use PHPdot\MongoDB\Config\MongoConfig;
use PHPdot\MongoDB\Database\Database;

$connection = new MongoConnection(new MongoConfig(
    hosts: 'localhost',
    database: 'myapp',
));
$connection->connect();

$users = (new Database($connection))->collection('users');

$users->insertOne(['name' => 'Omar', 'email' => '[email protected]']);

$user = $users->findOne(['email' => '[email protected]']);
echo $user->name; // 'Omar' — a Document with field access

$active = $users->find()
    ->filter(['status' => 'active'])
    ->sort(['created_at' => -1])
    ->limit(10)
    ->execute();

foreach ($active as $doc) {
    echo $doc->name;
}

$users->update()
    ->filter(['status' => 'pending'])
    ->set(['status' => 'active'])
    ->execute();

$users->delete()->filter(['status' => 'banned'])->execute();