Skip to content

PHPLIB-987: Add more examples #981

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Oct 4, 2022
Merged
2 changes: 2 additions & 0 deletions docs/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ following pages should help you get started:

- :doc:`/reference/bson`

Code examples can be found in the ``examples`` directory in the source code.

If you have previously worked with the legacy ``mongo`` extension, it will be
helpful to review the :doc:`/upgrade` for a summary of API changes between the
old driver and this library.
Expand Down
58 changes: 58 additions & 0 deletions examples/aggregate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);

namespace MongoDB\Examples;

use MongoDB\Client;

use function assert;
use function getenv;
use function is_object;
use function MongoDB\BSON\fromPHP;
use function MongoDB\BSON\toRelaxedExtendedJSON;
use function printf;
use function rand;

require __DIR__ . '/../vendor/autoload.php';

function toJSON(object $document): string
{
return toRelaxedExtendedJSON(fromPHP($document));
}

$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');

$collection = $client->test->coll;
$collection->drop();

$documents = [];

for ($i = 0; $i < 100; $i++) {
$documents[] = ['randomValue' => rand(0, 1000)];
}

$collection->insertMany($documents);

$pipeline = [
[
'$group' => [
'_id' => null,
'totalCount' => ['$sum' => 1],
'evenCount' => [
'$sum' => ['$mod' => ['$randomValue', 2]],
],
'oddCount' => [
'$sum' => ['$subtract' => [1, ['$mod' => ['$randomValue', 2]]]],
],
'maxValue' => ['$max' => '$randomValue'],
'minValue' => ['$min' => '$randomValue'],
],
],
];

$cursor = $collection->aggregate($pipeline);

foreach ($cursor as $document) {
assert(is_object($document));
printf("%s\n", toJSON($document));
}
78 changes: 78 additions & 0 deletions examples/bulk.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);

namespace MongoDB\Examples;

use MongoDB\Client;

use function assert;
use function getenv;
use function is_object;
use function MongoDB\BSON\fromPHP;
use function MongoDB\BSON\toRelaxedExtendedJSON;
use function printf;

require __DIR__ . '/../vendor/autoload.php';

function toJSON(object $document): string
{
return toRelaxedExtendedJSON(fromPHP($document));
}

$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');

$collection = $client->test->coll;
$collection->drop();

$documents = [];

for ($i = 0; $i < 10; $i++) {
$documents[] = ['x' => $i];
}

$collection->insertMany($documents);

$collection->bulkWrite(
[
[
'deleteMany' => [
['x' => ['$gt' => 7]], // Filter
],
],
[
'deleteOne' => [
['x' => 4], // Filter
],
],
[
'replaceOne' => [
['x' => 1], // Filter
['y' => 1], // Replacement
],
],
[
'updateMany' => [
['x' => ['$gt' => 5]], // Filter
['$set' => ['updateMany' => true]], // Update
],
],
[
'updateOne' => [
['x' => 2], // Filter
['$set' => ['y' => 2]], // Update
],
],
[
'insertOne' => [
['x' => 10], // Document
],
],
]
);

$cursor = $collection->find([]);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, Collection::find() can be called without arguments as $filter defaults to an empty array. This technically violates the CRUD spec but we snuck that past the goalie long ago. Up to you if you'd like to keep this as-is or change to find().

Likewise in with_transaction.php.


foreach ($cursor as $document) {
assert(is_object($document));
printf("%s\n", toJSON($document));
}
5 changes: 3 additions & 2 deletions examples/changestream.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@

namespace MongoDB\Examples;

require '../vendor/autoload.php';

use MongoDB\Client;

use function assert;
Expand All @@ -18,11 +16,14 @@

use const STDERR;

require __DIR__ . '/../vendor/autoload.php';

function toJSON(object $document): string
{
return toRelaxedExtendedJSON(fromPHP($document));
}

// Change streams require a replica set or sharded cluster
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');

$collection = $client->test->coll;
Expand Down
5 changes: 2 additions & 3 deletions examples/command_logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@

namespace MongoDB\Examples;

require '../vendor/autoload.php';

use MongoDB\Client;
use MongoDB\Driver\Monitoring\CommandFailedEvent;
use MongoDB\Driver\Monitoring\CommandStartedEvent;
Expand All @@ -22,12 +20,13 @@

use const STDERR;

require __DIR__ . '/../vendor/autoload.php';

function toJSON(object $document): string
{
return toRelaxedExtendedJSON(fromPHP($document));
}

// phpcs:disable Squiz.Classes.ClassFileName.NoMatch
class CommandLogger implements CommandSubscriber
{
public function commandStarted(CommandStartedEvent $event): void
Expand Down
109 changes: 109 additions & 0 deletions examples/persistable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?php
declare(strict_types=1);

namespace MongoDB\Examples;

use MongoDB\BSON\ObjectId;
use MongoDB\BSON\Persistable;
use MongoDB\Client;
use MongoDB\Model\BSONArray;
use UnexpectedValueException;

use function getenv;
use function var_dump;

require __DIR__ . '/../vendor/autoload.php';

class PersistableEntry implements Persistable
{
/** @var ObjectId */
private $id;

/** @var string */
public $name;

/** @var array<PersistableEmail> */
public $emails = [];

public function __construct(string $name)
{
$this->id = new ObjectId();
$this->name = $name;
}

public function getId(): ObjectId
{
return $this->id;
}

public function bsonSerialize(): object
{
return (object) [
'_id' => $this->id,
'name' => $this->name,
'emails' => $this->emails,
];
}

public function bsonUnserialize(array $data): void
{
if (! $data['_id'] instanceof ObjectId) {
throw new UnexpectedValueException('_id field is not of the expected type');
}

if (! $data['emails'] instanceof BSONArray) {
throw new UnexpectedValueException('emails field is not of the expected type');
}

$this->id = $data['_id'];
$this->name = (string) $data['name'];

/** @psalm-suppress MixedPropertyTypeCoercion */
$this->emails = $data['emails']->getArrayCopy(); // Emails will be passed as a BSONArray instance
}
}

class PersistableEmail implements Persistable
{
/** @var string */
public $type;

/** @var string */
public $address;

public function __construct(string $type, string $address)
{
$this->type = $type;
$this->address = $address;
}

public function bsonSerialize(): object
{
return (object) [
'type' => $this->type,
'address' => $this->address,
];
}

public function bsonUnserialize(array $data): void
{
$this->type = (string) $data['type'];
$this->address = (string) $data['address'];
}
}

$entry = new PersistableEntry('alcaeus');
$entry->emails[] = new PersistableEmail('work', 'alcaeus@example.com');
$entry->emails[] = new PersistableEmail('private', 'secret@example.com');

$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');

$collection = $client->test->coll;
$collection->drop();

$collection->insertOne($entry);

$foundEntry = $collection->findOne([]);

/** @psalm-suppress ForbiddenCode */
var_dump($foundEntry);
Loading