-
Notifications
You must be signed in to change notification settings - Fork 265
/
Copy pathchangestream.php
58 lines (41 loc) · 1.2 KB
/
changestream.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
declare(strict_types=1);
namespace MongoDB\Examples\ChangeStream;
use MongoDB\BSON\Document;
use MongoDB\Client;
use function assert;
use function getenv;
use function is_object;
use function printf;
use function time;
require __DIR__ . '/../vendor/autoload.php';
function toJSON(object $document): string
{
return Document::fromPHP($document)->toRelaxedExtendedJSON();
}
// Change streams require a replica set or sharded cluster
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
$collection = $client->test->changestream;
$collection->drop();
// Create collection before starting change stream; this is required on MongoDB 3.6
$client->test->createCollection('changestream');
$changeStream = $collection->watch();
$documents = [];
for ($i = 0; $i < 10; $i++) {
$documents[] = ['x' => $i];
}
$collection->insertMany($documents);
$changeStream->rewind();
$startTime = time();
while (true) {
if ($changeStream->valid()) {
$event = $changeStream->current();
assert(is_object($event));
printf("%s\n", toJSON($event));
}
$changeStream->next();
if (time() - $startTime > 3) {
echo "Aborting after 3 seconds...\n";
break;
}
}