==========================
MongoDB\\Database::watch()
==========================

.. versionadded:: 1.4

.. default-domain:: mongodb

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

Definition
----------

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

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

   .. code-block:: php

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

   This method has the following parameters:

   .. include:: /includes/apiargs/MongoDBDatabase-method-watch-param.rst

   The ``$options`` parameter supports the following options:

   .. include:: /includes/apiargs/MongoDBDatabase-method-watch-option.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';

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

   $changeStream = $database->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.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
--------

- :phpmethod:`MongoDB\\Collection::watch()`
- :phpmethod:`MongoDB\\Client::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
