定义
MongoDB\ChangeStream::current()返回变更流中的当前事件。
function current(): array|object|null每个事件文档的结构将根据操作类型而有所不同。 有关更多信息,请参阅MongoDB手册中的变更事件。
Return Values
变更流中当前事件的大量或对象,如果没有当前事件null即 MongoDB\ChangeStream::valid()返回false )。 返回类型将取决于 MongoDB\Collection::watch() 的typeMap选项
示例
此示例在迭代change stream时报告事件。
$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; }}假设在上述脚本迭代change stream时插入、更新和删除了文档,则输出将类似于以下内容:
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"}另请参阅
手册中的Change Streams 文档MongoDB
MongoDB 手册中的变更事件文档