Navigation
This version of the documentation is archived and no longer supported. To learn how to upgrade your version of PHP Library Manual, refer to the upgrade documentation.

MongoDB\Collection::watch()

New in version 1.3.

Definition

MongoDB\Collection::watch

Executes a change stream operation on the collection.

function watch(array $pipeline = [], array $options = []): MongoDB\ChangeStream

This method has the following parameters:

Parameter Type Description
$pipeline array|object Optional. The pipeline of stages to append to an initial $changeStream stage.
$options array Optional. An array specifying the desired options.

The $options parameter supports the following options:

Option Type Description
batchSize integer Optional. Specifies the maximum number of change events to return in each batch of the response from the MongoDB cluster.
collation array|object

Optional. Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, the locale field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.

If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

This option is available in MongoDB 3.4+ and will result in an exception at execution time if specified for an older server version.

fullDocument string

Optional. Allowed values are ‘default’ and ‘updateLookup’. Defaults to ‘default’. When set to ‘updateLookup’, the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. The following values are supported:

  • MongoDB\Operation\Watch::FULL_DOCUMENT_DEFAULT (default)
  • MongoDB\Operation\Watch::FULL_DOCUMENT_UPDATE_LOOKUP

Note

This is an option of the $changeStream pipeline stage.

maxAwaitTimeMS integer Optional. Positive integer denoting the time limit in milliseconds for the server to block a getMore operation if no data is available.
readConcern MongoDB\Driver\ReadConcern

Optional. Read concern to use for the operation. Defaults to the collection’s read concern.

This is not supported for server versions prior to 3.2 and will result in an exception at execution time if used.

readPreference MongoDB\Driver\ReadPreference

Optional. Read preference to use for the operation. Defaults to the collection’s read preference.

This is used for both the initial change stream aggregation and for server selection during an automatic resume.

resumeAfter array|object

Optional. Specifies the logical starting point for the new change stream.

Note

This is an option of the $changeStream pipeline stage.

session MongoDB\Driver\Session

Optional. Client session to associate with the operation.

Sessions are not supported for server versions prior to 3.6.

typeMap array Optional. The type map to apply to cursors, which determines how BSON documents are converted to PHP values. Defaults to the collection’s type map.

Return Values

A MongoDB\ChangeStream object, which allows for iteration of events in the change stream via the Iterator interface.

Errors/Exceptions

MongoDB\Exception\UnexpectedValueException if the command response from the server was malformed.

MongoDB\Exception\UnsupportedException if options are used and not supported by the selected server (e.g. collation, readConcern, writeConcern).

MongoDB\Exception\InvalidArgumentException for errors related to the parsing of parameters or options.

MongoDB\Driver\Exception\RuntimeException for other errors at the driver level (e.g. connection errors).

Examples

This example reports events while iterating a change stream.

<?php

$uri = 'mongodb://rs1.example.com,rs2.example.com/?replicaSet=myReplicaSet';

$collection = (new MongoDB\Client($uri))->test->inventory;

$changeStream = $collection->watch();

for ($changeStream->rewind(); true; $changeStream->next()) {
    if ( ! $changeStream->valid()) {
        continue;
    }

    $event = $changeStream->current();

    $ns = sprintf('%s.%s', $event['ns']['db'], $event['ns']['coll']);
    $id = json_encode($event['documentKey']['_id']);

    switch ($event['operationType']) {
        case 'delete':
            printf("Deleted document in %s with _id: %s\n\n", $ns, $id);
            break;

        case 'insert':
            printf("Inserted new document in %s\n", $ns);
            echo json_encode($event['fullDocument']), "\n\n";
            break;

        case 'replace':
            printf("Replaced new document in %s with _id: %s\n", $ns, $id);
            echo json_encode($event['fullDocument']), "\n\n";
            break;

        case 'update':
            printf("Updated document in %s with _id: %s\n", $ns, $id);
            echo json_encode($event['updateDescription']), "\n\n";
            break;
    }
}

Assuming that a document was inserted, updated, and deleted while the above script was iterating the change stream, the output would then resemble:

Inserted new document in test.inventory
{"_id":{"$oid":"5a81fc0d6118fd1af1790d32"},"name":"Widget","quantity":5}

Updated document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"}
{"updatedFields":{"quantity":4},"removedFields":[]}

Deleted document in test.inventory with _id: {"$oid":"5a81fc0d6118fd1af1790d32"}

See Also