MongoDB\Client::watch()

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

MongoDB\Client::watch()

New in version 1.4

Definition

Executes a change stream operation on the client. The change stream can be watched for cluster-level changes.

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

Parameters

$pipeline : array|object

The pipeline of stages to append to an initial $changeStream stage.

$options : array

An array specifying the desired options.

Name Type Description
batchSize integer The maximum number of documents within each batch returned in a change stream, which applies to the aggregate command. By default, the aggregate command has an initial batch size of 101 documents and a maximum size of 16 mebibytes (MiB) for each subsequent batch. This option can enforce a smaller limit than 16 MiB, but not a larger one. If you set batchSize to a limit that results in batches larger than 16 MiB, this option has no effect. Irrespective of the batchSize option, the initial aggregate command response for a change stream generally does not include any documents unless another option is used to configure its starting point (e.g. startAfter).
codec MongoDB\Codec\DocumentCodec The [Encode Data with Type Codecs](https://www.mongodb.com/docs/php-library/current/data-formats/custom-types/codecs.md#std-label-php-codecs to use for encoding or decoding documents. This option is mutually exclusive with the typeMap option. New in version 1.17
collation array|object 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.](https://www.mongodb.com/docs/manual/reference/collation/#collation-document
comment mixed Enables users to specify an arbitrary comment to help trace the operation through the database profiler, currentOp output, and logs. The comment can be any valid BSON type starting in MongoDB 4.4. Earlier server versions only support string values. New in version 1.13
fullDocument string Determines how the fullDocument response field will be populated for update operations. By default, change streams only return the delta of fields (via an updateDescription field) for update operations and fullDocument is omitted. Insert and replace operations always include the fullDocument field. Delete operations omit the field as the document no longer exists. Specify “updateLookup” to return the current majority-committed version of the updated document. Starting in MongoDB 6.0, you can access the post-image of the modified document if the collection has changeStreamPreAndPostImages enabled. Specify whenAvailable to return the post-image if available or a null value if not. Specify “required” to return the post-image if available or raise an error if not. The following values are supported: MongoDB\Operation\Watch::FULL_DOCUMENT_UPDATE_LOOKUP; MongoDB\Operation\Watch::FULL_DOCUMENT_WHEN_AVAILABLE; MongoDB\Operation\Watch::FULL_DOCUMENT_REQUIRED This is an option of the $changeStream pipeline stage.
fullDocumentBeforeChange string Determines how the fullDocumentBeforeChange response field will be populated. By default, the field is omitted. MongoDB 6.0+ allows returning the pre-image of the modified document if the collection has changeStreamPreAndPostImages enabled. Specify “whenAvailable” to return the pre-image if available or a null value if not. Specify “required” to return the pre-image if available or raise an error if not. The following values are supported: MongoDB\Operation\Watch::FULL_DOCUMENT_BEFORE_CHANGE_WHEN_AVAILABLE; MongoDB\Operation\Watch::FULL_DOCUMENT_BEFORE_CHANGE_REQUIRED This is an option of the $changeStream pipeline stage. New in version 1.13
maxAwaitTimeMS integer 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 Read concern to use for the operation. Defaults to the client's read concern.
readPreference MongoDB\Driver\ReadPreference Read preference to use for the operation. Defaults to the client's read preference. This is used for both the initial change stream aggregation and for server selection during an automatic resume.
resumeAfter array|object Specifies the logical starting point for the new change stream. The _id field in documents returned by the change stream may be used here. Using this option in conjunction with startAfter and/or startAtOperationTime will result in a server error. The options are mutually exclusive. This is an option of the $changeStream pipeline stage.
session MongoDB\Driver\Session Client session to associate with the operation.
showExpandedEvents boolean If true, instructs the server to include additional DDL events in the change stream. The additional events that may be included are: createIndexes; dropIndexes; modify; create; shardCollection; reshardCollection (server 6.1+); refineCollectionShardKey (server 6.1+) This is not supported for server versions prior to 6.0 and will result in an exception at execution time if used. This is an option of the $changeStream pipeline stage. New in version 1.13
startAfter array|object Specifies the logical starting point for the new change stream. The _id field in documents returned by the change stream may be used here. Unlike resumeAfter, this option can be used with a resume token from an “invalidate” event. Using this option in conjunction with resumeAfter and/or startAtOperationTime will result in a server error. The options are mutually exclusive. This is an option of the $changeStream pipeline stage. New in version 1.5
startAtOperationTime MongoDB\BSON\TimestampInterface If specified, the change stream will only provide changes that occurred at or after the specified timestamp. By default, the operationTime returned by the initial aggregate command will be used if available. Using this option in conjunction with resumeAfter and/or startAfter will result in a server error. The options are mutually exclusive. To use this option, you must connect to MongoDB 6.0 or later. If you are connected to an earlier version, the server returns an exception at execution time. This is an option of the $changeStream pipeline stage.
typeMap array The [type map](https://php.net/manual/en/mongodb.persistence.deserialization.php#mongodb.persistence.typemaps to apply to cursors, which determines how BSON documents are converted to PHP values. Defaults to the client's type map.

Return Values

A [MongoDB\ChangeStream](https://www.mongodb.com/docs/php-library/current/reference/class/mongodbchangestream.md#mongodb-phpclass-phpclass.MongoDB-ChangeStream object, which allows for iteration of events in the change stream via the Iterator interface.

Errors/Exceptions

[MongoDB\Exception\UnexpectedValueException](https://www.mongodb.com/docs/php-library/current/reference/exception-classes.md#mongodb-phpclass-phpclass.MongoDB-Exception-UnexpectedValueException if the command response from the server was malformed.

[MongoDB\Exception\UnsupportedException](https://www.mongodb.com/docs/php-library/current/reference/exception-classes.md#mongodb-phpclass-phpclass.MongoDB-Exception-UnsupportedException if options are used and not supported by the selected server (e.g. collation, readConcern, writeConcern).

[MongoDB\Exception\InvalidArgumentException](https://www.mongodb.com/docs/php-library/current/reference/exception-classes.md#mongodb-phpclass-phpclass.MongoDB-Exception-InvalidArgumentException for errors related to the parsing of parameters or options.

MongoDB\Driver\Exception\RuntimeException for other errors at the extension 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';

$client = new MongoDB\Client($uri);

$changeStream = $client->watch();

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

    $event = $changeStream->current();

    if ($event['operationType'] === 'invalidate') {
        break;
    }

    $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 app.user
{"_id":{"$oid":"5b329b6674083047cc05e607"},"username":"bob"}

Inserted new document in app.products
{"_id":{"$oid":"5b329b6a74083047cc05e608"},"name":"Widget","quantity":5}

Inserted new document in logs.messages
{"_id":{"$oid":"5b329b7374083047cc05e609"},"msg":"bob purchased a widget"}

See Also

  • [MongoDB\Collection::watch()](https://www.mongodb.com/docs/php-library/current/reference/method/mongodbcollection-watch.md#mongodb-phpmethod-phpmethod.MongoDB-Collection--watch--

  • [MongoDB\Database::watch()](https://www.mongodb.com/docs/php-library/current/reference/method/mongodbdatabase-watch.md#mongodb-phpmethod-phpmethod.MongoDB-Database--watch--

  • Aggregation Pipeline documentation in the MongoDB Manual

  • Change Streams documentation in the MongoDB manual

  • Change Events documentation in the MongoDB manual