UpdateMany.php 2.06 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
<?php

namespace MongoDB\Operation;

use MongoDB\UpdateResult;
use MongoDB\Driver\Server;
use MongoDB\Exception\InvalidArgumentException;

/**
 * Operation for updating multiple documents with the update command.
 *
 * @api
 * @see MongoDB\Collection::updateMany()
 * @see http://docs.mongodb.org/manual/reference/command/update/
 */
class UpdateMany implements Executable
{
    private $update;

    /**
     * Constructs an update command.
     *
     * Supported options:
     *
25 26 27
     *  * bypassDocumentValidation (boolean): If true, allows the write to opt
     *    out of document level validation.
     *
28 29 30 31 32 33 34 35 36 37 38 39
     *  * upsert (boolean): When true, a new document is created if no document
     *    matches the query. The default is false.
     *
     *  * writeConcern (MongoDB\Driver\WriteConcern): Write concern.
     *
     * @param string       $databaseName   Database name
     * @param string       $collectionName Collection name
     * @param array|object $filter         Query by which to filter documents
     * @param array|object $update         Update to apply to the matched documents
     * @param array        $options        Command options
     * @throws InvalidArgumentException
     */
Jeremy Mikola's avatar
Jeremy Mikola committed
40
    public function __construct($databaseName, $collectionName, $filter, $update, array $options = [])
41 42
    {
        if ( ! is_array($update) && ! is_object($update)) {
43
            throw InvalidArgumentException::invalidType('$update', $update, 'array or object');
44 45 46 47 48 49 50 51 52 53 54
        }

        if ( ! \MongoDB\is_first_key_operator($update)) {
            throw new InvalidArgumentException('First key in $update argument is not an update operator');
        }

        $this->update = new Update(
            $databaseName,
            $collectionName,
            $filter,
            $update,
Jeremy Mikola's avatar
Jeremy Mikola committed
55
            ['multi' => true] + $options
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
        );
    }

    /**
     * Execute the operation.
     *
     * @see Executable::execute()
     * @param Server $server
     * @return UpdateResult
     */
    public function execute(Server $server)
    {
        return $this->update->execute($server);
    }
}