============================
MongoDB\\Collection::watch()
============================

.. versionadded:: 1.3

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 1
   :class: singlecol

Definition
----------

.. phpmethod:: MongoDB\Collection::watch()

   Executes a :manual:`change stream </changeStreams>` operation on the
   collection. The change stream can be watched for collection-level changes.

   .. code-block:: php

      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.

  .. list-table::
     :header-rows: 1
     :widths: 20 20 80

     * - Name
       - Type
       - Description

     * - batchSize
       - integer
       - .. include:: /includes/extracts/watch-option-batchSize.rst

     * - codec
       - MongoDB\\Codec\\DocumentCodec
       - .. include:: /includes/extracts/collection-option-codec.rst

         .. versionadded:: 1.17

     * - collation
       - array|object
       - .. include:: /includes/extracts/common-option-collation.rst

         Starting in MongoDB 4.2, defaults to simple binary comparison if
         omitted. In earlier versions, change streams opened on a single
         collection would inherit the collection's default collation.

     * - comment
       - mixed
       - .. include:: /includes/extracts/common-option-comment.rst
  
         .. include:: /includes/extracts/common-option-comment-string-before-4.4.rst

         .. versionadded:: 1.13

     * - fullDocument
       - string
       - .. include:: /includes/extracts/watch-option-fullDocument.rst

     * - fullDocumentBeforeChange
       - string
       - .. include:: /includes/extracts/watch-option-fullDocumentBeforeChange.rst

     * - maxAwaitTimeMS
       - integer
       - .. include:: /includes/extracts/watch-option-maxAwaitTimeMS.rst

     * - readConcern
       - :php:`MongoDB\Driver\ReadConcern <class.mongodb-driver-readconcern>`
       - .. include:: /includes/extracts/collection-option-readConcern.rst

     * - readPreference
       - :php:`MongoDB\Driver\ReadPreference <class.mongodb-driver-readpreference>`
       - .. include:: /includes/extracts/collection-option-readPreference.rst

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

     * - resumeAfter
       - array|object
       - .. include:: /includes/extracts/watch-option-resumeAfter.rst

     * - session
       - :php:`MongoDB\Driver\Session <class.mongodb-driver-session>`
       - .. include:: /includes/extracts/common-option-session.rst

     * - showExpandedEvents
       - boolean
       - .. include:: /includes/extracts/watch-option-showExpandedEvents.rst

     * - startAfter
       - array|object
       - .. include:: /includes/extracts/watch-option-startAfter.rst

     * - startAtOperationTime
       - :php:`MongoDB\BSON\TimestampInterface <class.mongodb-bson-timestampinterface>`
       - .. include:: /includes/extracts/watch-option-startAtOperationTime.rst

     * - typeMap
       - array
       - .. include:: /includes/extracts/collection-option-typeMap.rst

Return Values
-------------

A :phpclass:`MongoDB\ChangeStream` object, which allows for iteration of
events in the change stream via the :php:`Iterator <class.iterator>` interface.

Errors/Exceptions
-----------------

.. include:: /includes/extracts/error-unexpectedvalueexception.rst
.. include:: /includes/extracts/error-unsupportedexception.rst
.. include:: /includes/extracts/error-invalidargumentexception.rst
.. include:: /includes/extracts/error-driver-runtimeexception.rst

Examples
--------

This example reports events while iterating a change stream.

.. code-block:: php

   <?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();

       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:

.. code-block:: none

   Inserted new document in test.user
   {"_id":{"$oid":"5b329c4874083047cc05e60a"},"username":"bob"}

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

   Updated document in test.user with _id: {"$oid":"5b329a4f74083047cc05e603"}
   {"updatedFields":{"username":"robert"},"removedFields":[]}

See Also
--------

- :phpmethod:`MongoDB\Client::watch()`
- :phpmethod:`MongoDB\Database::watch()`
- :manual:`Aggregation Pipeline </core/aggregation-pipeline>` documentation in
  the MongoDB Manual
- :manual:`Change Streams </changeStreams>` documentation in the MongoDB manual
- :manual:`Change Events </reference/change-events/>` documentation in the
  MongoDB manual
