Collection-bulkWrite.php 2.26 KB
Newer Older
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
<?php
require __DIR__ . "/" . "../vendor/autoload.php";

function dumpWriteResults(MongoDB\WriteResult $result) {
    printf("Inserted %d documents, upserted %d, updated %d and deleted %d\n",
        $result->getInsertedCount(), $result->getUpsertedCount(),
        $result->getModifiedCount(), $result->getDeletedCount()
    );

    if ($result->getUpsertedCount()) {
        foreach ($result->getUpsertedIds() as $index => $id) {
            printf("upsertedId[%d]: %s", $index, $id);
        }
    }
}
function dumpCollection($collection) {
    printf("\n---\nDumping all documents in: %s.%s\n",
        $collection->getDatabaseName(),
        $collection->getCollectionName()
    );
    $n = 0;
    foreach($collection->find() as $document) {
        var_dump($document);
        $n++;
    }
    printf("Found %d documents\n", $n);
}


$manager = new MongoDB\Manager("mongodb://localhost:27017");
$collection = new MongoDB\Collection($manager, "crud.bulkWrite");
$result = $collection->bulkWrite([
    [
        "insertOne" => [
            [
                "name" => "Hannes Magnusson",
                "company" => "10gen",
            ]
        ],
    ],
    [
        "insertOne" => [
            [
                "name" => "Jeremy Mikola",
                "company" => "10gen",
            ]
        ],
    ],
    [
        "updateMany" => [
            ["company" => "10gen"],
            ['$set' => ["company" => "MongoDB"]],
        ],
    ],
    [
        "updateOne" => [
            ["name" => "Hannes Magnusson"],
            ['$set' => ["viking" => true]],
        ],
    ],
]);

dumpWriteResults($result);
dumpCollection($collection);


$result = $collection->bulkWrite([
    [
        "deleteOne" => [
            ["company" => "MongoDB"],
        ],
    ],
    [
        "updateOne" => [
            ["name" => "Hannes Magnusson"],
            ['$set' => ["nationality" => "Icelandic"]],
            ["upsert" => true],
        ],
    ],
    [
        "deleteMany" => [
            ["nationality" => [ '$ne' => "Icelandic"]],
        ],
    ],
]);

echo "\n\n";
dumpWriteResults($result);
dumpCollection($collection);

$result = $collection->bulkWrite([
    [
        "deleteMany" => [
            [],
        ],
    ],
]);

echo "\n\n";
dumpWriteResults($result);
dumpCollection($collection);