MongoDBChangeStream-key.txt 1.7 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 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
============================
MongoDB\\ChangeStream::key()
============================

.. default-domain:: mongodb

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

Definition
----------

.. phpmethod:: MongoDB\\ChangeStream::key()

   Returns the index of the current event in the change stream.

   .. code-block:: php

      function key(): integer|null

   The index of the first event in a change stream starts at zero and will
   increment by one for each subsequent event.

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

The index of the current event in the change stream, or ``null`` if there is no
current event (i.e. :phpmethod:`MongoDB\\ChangeStream::valid()` returns
``false``).

Examples
--------

This example reports the index of 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();

       printf("%d: %s\n", $changeStream->key(), $event['operationType']);
   }

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

   0: insert
   1: update
   2: delete

See Also
--------

- :phpmethod:`MongoDB\\Collection::watch()`
- :php:`Iterator::key() <iterator.key>`
- :ref:`Tailable Cursor Iteration <php-tailable-cursor>`
- :manual:`Change Streams </changeStreams>` documentation in the MongoDB manual