Skip to content

Commit 76f3931

Browse files
committed
Add aggregation example
1 parent ad6d94e commit 76f3931

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

examples/aggregate.php

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
namespace MongoDB\Examples;
5+
6+
use MongoDB\Client;
7+
8+
use function assert;
9+
use function dirname;
10+
use function getenv;
11+
use function is_object;
12+
use function MongoDB\BSON\fromPHP;
13+
use function MongoDB\BSON\toRelaxedExtendedJSON;
14+
use function printf;
15+
use function rand;
16+
17+
require dirname(__FILE__) . '/../vendor/autoload.php';
18+
19+
function toJSON(object $document): string
20+
{
21+
return toRelaxedExtendedJSON(fromPHP($document));
22+
}
23+
24+
$client = new Client(getenv('MONGODB_URI') ?: 'mongodb://127.0.0.1/');
25+
26+
$collection = $client->test->coll;
27+
$collection->drop();
28+
29+
$documents = [];
30+
31+
for ($i = 0; $i < 100; $i++) {
32+
$documents[] = ['randomValue' => rand(0, 1000)];
33+
}
34+
35+
$collection->insertMany($documents);
36+
37+
$pipeline = [
38+
[
39+
'$group' => [
40+
'_id' => null,
41+
'totalCount' => ['$sum' => 1],
42+
'evenCount' => [
43+
'$sum' => ['$mod' => ['$randomValue', 2]],
44+
],
45+
'oddCount' => [
46+
'$sum' => ['$subtract' => [1, ['$mod' => ['$randomValue', 2]]]],
47+
],
48+
'maxValue' => ['$max' => '$randomValue'],
49+
'minValue' => ['$min' => '$randomValue'],
50+
],
51+
],
52+
];
53+
54+
$cursor = $collection->aggregate($pipeline, ['batchSize' => 2]);
55+
56+
foreach ($cursor as $document) {
57+
assert(is_object($document));
58+
printf("%s\n", toJSON($document));
59+
}

0 commit comments

Comments
 (0)