文档菜单
文档首页
/ / /
PHP 库手册
/ / /

MongoDB\ChangeStream::current()

本页内容

  • 定义
  • 返回值
  • 示例
  • 另请参阅
MongoDB\ChangeStream::current()

返回变更流中的当前事件。

function current(): array|object|null

每个事件文档的结构将根据操作类型而有所不同。请参阅变更事件中的MongoDB手册以获取更多信息。

一个数组或对象,表示变更流中的当前事件,如果没有当前事件(即MongoDB\ChangeStream::valid()返回false),则返回null。返回类型将取决于MongoDB\Collection::watch()typeMap选项。MongoDB\ChangeStream::valid()

此示例在遍历变更流时报告事件。

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

返回

ChangeStream 类