AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

MongoDB\ChangeStream::current()

MongoDB\ChangeStream::current()

変更ストリーム内の現在のイベントを返します。

function current(): array|object|null

各イベントドキュメントの構造は、操作の種類によって異なります。 詳細については、 MongoDBマニュアルの「変更イベント」を参照してください。

変更ストリーム内の現在のイベントの配列またはオブジェクト、または現在のイベントがない場合はnull ( MongoDB\ChangeStream::valid()はfalse を返します)。戻り値の型は、MongoDB\Collection::watch() のtypeMapオプションによって異なります

この例では、変更ストリームを反復処理しながらイベントを報告します。

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

上記のスクリプトが変更ストリームを反復処理している間にドキュメントが挿入、更新、および削除されたと仮定すると、出力は次のようになります。

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"}