For AI agents: a documentation index is available at https://www.mongodb.com/ko-kr/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
MongoDB Branding Shape
Click here >
Docs Menu

MongoDB\ChangeStream::key()

MongoDB\ChangeStream::key()

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

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.

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

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

0: insert
1: update
2: delete